I have a REST API on AWS which calls a lambda function to update something in the database. It can return either 200 (success) or other errors. In my React app, I want to make a PUT call to the API and check the status once it returns.
Here is the response from the lambda:
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers' : 'Content-Type',
'Access-Control-Allow-Origin': 'http://localhost:3000',
'Access-Control-Allow-Methods': 'PUT'
}
}
Here is what I have so far:
import { API } from 'aws-amplify'
async function onButtonClick() {
const response = await API.put('myapi', 'endpoint')
if(response['statusCode'] === 200){
console.log("Completed!")
}
}
However, although the request to the API is sent, and the database is updated, in my React app it never triggers that if statement. Checking the response by logging it to the console it looks like an empty string?
Related
I make a call to an API using the Amplify API:
import { API } from 'aws-amplify'
await API.get('myapi', 'endpoint')
.then(data => {
// Do something here
})
When my API returns 200 and some data back, then the then body is executed successfully. The problem is, when the endpoint returns 404 (or better non-200 response), it seems like the await API.get .... is not returning and therefore the then body is never executed. I can see in the developer tools and in the Network tab that the call indeed returned a 404 error, it's just in React it never triggers the then body.
This is what the API returns:
return {
'statusCode': 404,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Headers' : 'Content-Type',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET'
}
}
.then() is triggered when your request is successful and .catch() is triggered when request is rejected.
import { API } from 'aws-amplify'
await API.get('myapi', 'endpoint')
.then(data => {
// Do something here
})
.catch((err) => {
console.log(err);
});
Plus, I don't think using await along with .then() is a good practice.
.then().catch() and async/await are 2 popular ways of handling asynchronous executions.They should not be mixed with each other.
Reference link : https://www.geeksforgeeks.org/difference-between-promise-and-async-await-in-node-js/?ref=lbp
I am using axios to make apis calls in react. If there is no token provided or token got expired server sends the 401 status. I want to check that status on reactjs side.
But if i check err object in catch the status field is null.
Here is the code
try {
MyService.getIntet(reqBody);
} catch (err) {
handleUnAuthorizedResponse(err);
}
on the error this shows this type of info.
In the service
import axios from "axios";
and the function
static getIntent(reqBody) {
const url = `${this.intentionBaseUrl}/process`;
const options = {
headers: {
"Content-Type": "application/json"
},
};
return axios
.post(url, reqBody, options)
.then((res) => res.data)
}
HOw can i handle 401?
The error you've logged does not have a status because the request ended in a Network Error, which is not a 401.
You could check if it's a CORS problem, or else.
Otherwise, to manage the 401, seems good to use the handleUnAuthorizedResponse passing the error that should contain:
const err = {
..., // other things like the request etc
code: 'ERR_BAD_REQUEST',
response: {
status: 401, // status code
statusText: 'Unauthorized',
data: {} // data if the server sends some, like error messages, etc
}
}
I am getting the CORS access error in my React Native app when connecting to an external API.
async componentDidMount() {
// POST request using fetch with async/await
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify({ type:'accountLookup',storeId:STORE_ID, storeKey:STORE_KEY, memberId:'471324' })
};
const response = await fetch('http://frequent5.revlogical.com/wsMobile', requestOptions);
const data = await response.json();
this.setState({ data: data });
The problem is most likely not with React app, rather with your server which is not configurated to serve your app.
You should set 'Access-Control-Allow-Origin' header on your server to allow your app's address to make requests.
This problem is usually the fault of the backend. Test it with a tool like https://www.test-cors.org/
An alternative is to create a server to be intercepted between the frontend and the API, and you can handle this guy's cors
So, I am using ReactJS and DjangoRESTframework to build my app.
Now..when I send a request with Postman it works perfectly(ex. 127.0.0.1:8000/api/users/ GET request) and when I try to do it in React with Axios I get a network error but on my local development server console I see that it succeeded.
This is my get request with axios in react:
componentDidMount() {
axios.get('http://127.0.0.1:8000/api/users/', {
headers: {
'Accept': 'application/json'
}
})
.then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
})
}
And I get an Network Error. But as I said with Postman it works.
One more example is that I send POST request with Axios to http://127.0.0.1:8000/api/users/ and as response I get Network Error as well but on my backend, user IS created.
This is code for my POST request with axios:
let formData = new FormData();
formData.set('email', this.state.emailField);
formData.set('username', this.state.usernameField);
formData.set('password', this.state.passwordField);
axios({
method: 'POST',
data: formData,
url: 'http://127.0.0.1:8000/api/users/',
config: {headers: {'Content-Type': 'multipart/form-data'}}
}).then(request => {
console.log(request.data);
}).catch(err => {
console.log(err);
})
I googled for about an hour to fix this but nothing helps.
Can you be more clear on what you see as Network error? Attach some error messages / Stack trace.
This looks like a Cross-Origin Resource Sharing (CORS)
issue to me. Try configuring CORS on your DjangoRESTframework backend.
This might help you if that is the case.
I am just trying to get the CORS headers issue caused by missing headers in request out of the way and hence inclined to using JSONP.
Any suggestions/ideas how to use JSONP in a react-redux app? Like how to configure and use it?
In your react component, dispatch an action that is caught by middleware. The middleware should make a call to the jsonp endpoint, probably using jquery's $.ajax method. I also like the fetchJsonp library. Your middleware should then dispatch a new action with the data received by ajax or fetchJsonp, which should be caught by your reducer, and alter the state.
I use fetch in most of cases in react apps:
// payload is your post data
const payload = {data: 'test'};
const options = {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
cors: true, // allow cross-origin HTTP request
credentials: 'same-origin' // This is similar to XHR’s withCredentials flag
};
// SEND REQUEST
fetch('http://example.com/', options).then((response) => {
// TODO
}).catch((error) => {
// TODO
});