Receive JSON content of Fetch API Post call - reactjs

I am new to React and I have a chat UI in which I am trying to test an API call from a service.
Please assume that the call itself have the correct parameters, and even if not I want to see the error JSON response and I am just getting a blank message in the chat as a response to the user message.
The call working through Postman app in chrome but when trying to assign the call result to var in react it doesn't present the JSON response value when trying to post the message through the UI chat.
This is the function, the user message transfered to this function and then an answer should appear right after via the fetched API request:
submitMessage(e) {
e.preventDefault();
var s = fetch('https://***', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': '****',
},
body: JSON.stringify({ inputText: 'hi' })
});
this.setState({
chats: this.state.chats.concat([
{
username: "newUser",
content: <p>{ReactDOM.findDOMNode(this.refs.msg).value}</p>
},
{
username: "responsePlace",
content: s
}
])
});
}

fetch is a javascript Promise therefore it needs to be resolved using then
fetch(...)
.then(response => response.json()) // resolves json content of the response
.then(data => console.log(data)) // your actual data as a javascript object
.catch(ex => console.log(ex)) // exception handler in case anything goes wrong in the fetch
More on fetch api: fetch api examples
More on Promises: Promises

Related

json server fake rest api with POST

I am using JSON server fake rest API and having issues with POST method. When I use to submit the form, the data should be added to the API. In the console.log it shows the data so it means that the promise has been executed but that data is not added to API. Following is the POST method i am using:
fetch("https://my-json-server.typicode.com/<github_id>/<github_repo>/blogs/", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(blog),
}).then(() => {
console.log("blog added");
console.log(blog);
setTitle("");
setBody("");
setAuthor("adam");
setIsLoading(false);
history.push("/");
});

React / Strapi - API request put data in the CMS

Quick question: I made a API fetch function for my Strapi CMS but can't seem to get the right JSON.
This results in my API call adding a new item within the Strapi CMS (200 OK HTTP). But without the provided data. I'm guessing that the JSON is wrongly formatted and the data gets lost.
What works:
Authorization works
API request works (200)
There is an empty article within the Strapi CMS
What doesn't work:
Data doesn't get set within the CMS.
The code:
// POST request using fetch with error handling
function setArticle() {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${state.jwt}`
},
body: JSON.stringify({
slug: "first-success",
name: "First successful API request"
})
};
fetch('http://localhost:1337/articles', requestOptions)
.then(async response => {
const data = await response.json();
console.log(requestOptions);
// check for error response
if (!response.ok) {
// get error message from body or default to response status
const error = (data && data.message) || response.status;
return Promise.reject(error);
}
this.setState({ postId: data.id })
})
.catch(error => {
console.error('There was an error!');
});
}
What I tried, logging and reading the Strapi documentation.
The problem was, case sensitivity. Apparently when making a new content type within Strapi I set the entity with an uppercase. (Slug and Name) resulting to my body within my HTTP request getting ignore.
I changed the Strapi fields without an uppercase and it's now working.
body: JSON.stringify({
slug: "first-success",
name: "First successful API request"
})

Body of request received on Express backend is different than how i sent it from React frontend

I am trying to send a post request from my React front end to my Express front end, for some reason, the object I want to recieve, is being displayed so that the object is the key of another object and the value is and empty string.
Here is my onSubmit React function
handleSubmit = event => {
event.preventDefault()
const backend = '/api/login'
fetch(backend, {
method: 'POST',
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
},
body: JSON.stringify(this.state)
})
.then(res => {
res.json()
})
.then(user => {
console.log(user)
})
.catch(err => {
console.log(err)
})
}`
And my post function on the express server
app.post("/login", (req, res) => {
console.log(req.body)
})
For example, if the object I want to send is {username: "user1", password: "password"}, when I console.log(req.body), I get { '{"username":"user1","password":"password"}': '' } in the console.
How do i fix this so i get the object that I requested?
Because it is JSON format. To parse it you can use:
JSON.parse('{"username":"user1","password":"password"}')
or JSON.parse(req.body)
The approach is fine with JSON.stringify() because it should be posted just like a string to the server. But if you want it to be an object at the backend then you have to parse it back with:
const userObj = JSON.parse(req.body.Data); // it will parse it back as an object

Can't access the data returned by api call to http://dummy.restapiexample.com/api/v1/employee/3

I`m trying to model an application for managing the employees of a company. My problem: I'm trying to fetch the data of a specific user, calling the API endpoint : http://dummy.restapiexample.com/api/v1/employee/3 (the 3 can be replaced by other user-ids).
When I'm calling the endpoint from Postman I get this response
But when I try to access the same resource from my React application I get this response.
Here is how I call the API endpoint
export async function getSingleEmployee() {
return fetch('http://dummy.restapiexample.com/api/v1/employee/3', {
mode: 'cors',
method: 'GET',
dataType: 'json',
headers: {
'Access-Control-Allow-Origin':'*',
'Content-type': 'application/json;charset=utf-8',
}
})
.then(response => response)
.then(data => {
console.log(data);
})}
How can I access the data as I do in the Postman request? What am I missing?
Did you try using "await" fetch.... ?

How to pass authentication token with every React request to back end API?

I have an existing application in which REST APIs are already developed. I am thinking to develop a front end using React JS and front end should call my REST APIs with every request.
However when I login to my application then a token is generated which is passed to every subsequent requests as an authentication header. How can I achieve this using React?
I am a beginner in React.
You can use axios as a library, and add this as a configuration
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`
https://www.npmjs.com/package/axios
Use fetch. Example:
var data = {myData: 'hello'}; // or just 'hello'
fetch(YOUR_URL, {
method: 'POST', // or GET
body: JSON.stringify(data), // data can be string or object
headers:{
'Authorization': YOUR_TOKEN,
// ... add other header lines like: 'Content-Type': 'application/json'
}
}).then(res => res.json()) // if response is json, for text use res.text()
.then(response => console.log('Response:', JSON.stringify(response))) // if text, no need for JSON.stringify
.catch(error => console.error('Error:', error));
First receive the token and save it to your browsers local storage using localStorage.setItem('token', JSON.stringify(userToken));
Then, everytime you send a request, you get this token from your local storage using localStorage.getItem("token")
Thereafter, if you were POSTing an object with a key value of ID: 1, you would do:
await fetch("your_API_endpoint", {
method: 'POST',
headers: { 'Content-Type': 'application/json', "Authorization": localStorage.getItem("token") },
body: JSON.stringify({'ID': '1'})
})

Resources