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

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.... ?

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("/");
});

Problems using uri on axios

I currently work with an api rest where I pass the controller parameters, version and action via URI. However, when I execute a request with URI with more than 19 characters, it gives this CORS error:
Access to XMLHttpRequest at 'http://my-api-host/toll/vehicle/v1/list' from origin 'http://localhost: 3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
In authentication the request works even with URI having more than 19 characters. However, any other request with a different URI that has more than 19 characters gives this same error. I use my application's API and the request works normally.
I'm using axios in Reactjs.
The api is already configuring to accept the content-type I am using (application / json) and is also already accepting requests from different sources.
My request code:
request(uri, params = {}){
return new Promise((resolve, reject) => {
axios
.post('http://my-api-host' + uri, JSON.stringify(params), {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
if (response.data.success) {
resolve(response.data);
} else {
reject(response.data);
}
});
});
};
Has anyone been through this and could help? thanks in advance
Did you use Fetch instead?
async function postData(url = '', params = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
headers: {
'Content-Type': 'application/json'
},
qs: JSON.stringify(params) // query string data
});
return response.json(); // parses JSON response into native JavaScript objects
}
postData('http://my-api-host', params)
.then(data => {
console.log(data);
});

API request working in Postman but not in fetch() method of React Native app

I am trying to do a fetch() method in my React Native app:
return fetch(url, {
method: method,
headers: {
'Accept': 'application/json',
...headers
},
body: body
})
Here url is <IP address>:<port>/api/token
method is 'POST'
headers is {Content-Type: "application/x-www-form-urlencoded"}
and body is
grant_type=password&username=<username>&password=<password>&pushtoken=&primaryhost=<primary host IP>&primaryport=<primary host port>&secondaryhost=<secondary host IP>&secondaryport=<secondary host port>&osscustomer=103&deviceid=<device ID>&version=1.0&osversion=9&deviceversion=1.0
When I use these values in a Postman request, it works fine, but when I run the fetch() method in my React Native app, it gives the error e = TypeError: Network request failed at XMLHttpRequest.xhr.onerror.
Does anyone know why this might be?
change 'Accept' to Accept without single quites.
In the latest android versions http requests are not allowed by default. Take a look at this post for further information about allowing http request:How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?
Use the following format:
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
Better to use axios for http/https requests:axios package
It's working fine for me. Try this it may help
const formData = new FormData();
formData.append('email', 'test#gmail.com');
formData.append('password', '123456');
fetch("https://test.com/api/login", {
method: 'post',
body: formData
})
.then(res => res.json())
.then(
(result) => {
console.log(result);
}).catch(err => {
console.log(err);
})

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'})
})

Receive JSON content of Fetch API Post call

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

Resources