I keep getting status 400 bad request - reactjs

I am trying to use fetch function with post method to send some data to an api endpoint which is in my local, the problem is when I used client side to test the endpoint & the link I got successful response , however when I use it in my react app I keep getting status 400 bad request
what do you think the problem is?
my request code in my app:
const onClick=async()=>{
try{
let result=await fetch("http://127.0.0.1:3000/api/send",{
method:"POST",
headers:{
"Accept":"application/json",
"Content-type":"application/json;",
},
body:{
"emails": [
"aaa#aaa.com",
"bbb#bbb.com"
]
}
});

Related

Unable to fetch data from AWS api gateway with python lambda function to react js frontend using axios

I am trying to access data from AWS api gateway. Which works fine without an api-key but after the api-key is enabled the data is not retrived from the server while it works alright with postman testing.
The error in the browser is shows as follows ->
Access to XMLHttpRequest at 'https://bvoj5hykj0.execute-api.us-east-1.amazonaws.com/test/testresource' 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.
The server-side lambda function python code is given as follows
import json
def lambda_handler(event,context):
return {
'statusCode': 200,
'headers':{
"Access-Control-Allow-Origin": "*",
"Content-Type" : "application/json",
"Access-Control-Allow-Headers" : "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token,x-api-key",
"Access-Control-Allow-Methods" : "GET"
"Content-Type" : "application/json"
},
'body': json.dumps("changes saved")
}
The react axios code to retrive the data using api-key is as follows ->
async function testAct(){
// The below code block is also been tried and returns same response
// axios.defaults.headers.common = {
// "x-api-key": "xxxxxxxxxxxxxxxxxxxxx"
// }
// const headers = {
// "Content-Type": "application/json",
// "Authorization": "xxxxxxxxx-here-is-my-api-keyxxxxx"
// };
await axios.get("here is aws-api-url-hidden",{
headers: {
"x-api-key": "xxxxxxxxx-here-is-my-api-keyxxxxx"
}
})
.then((response) => {
console.log(response);
setTestRes(response.data);})
.catch((error) => { console.log(error);});
}
The API key and API url is right [ I have checked several times ]
The postman response is alright as below ->
without api-key->
with api-key
I was trying to get the data with aws api-key in reactjs front end. The data comes just fine with postman testing but fails inside react js.
Depending on the API Gateway to Lambda integration configuration, you will also need to enable CORS for API Gateway. This will handle the preflight OPTIONS request as noted by a previous commenter. The browser will perform the OPTIONS check, but Postman (to my knowledge) will not.
A few resources to help you configure API Gateway:
https://docs.aws.amazon.com/apigateway/latest/developerguide/how-to-cors.html
https://aws.amazon.com/blogs/compute/configuring-cors-on-amazon-api-gateway-apis/

Django server unable to get data from react Axios

I'm not getting an error but when I saw the logs of my server it prints an empty object {} whenever I send a request to the sever from my react app using axios. I double checked everything every other request in another components of my app works fine, but only in this particular request the data is not being sent! I have no CORS issue!
My react axios request
// PrivateAxios instance to send api request
const axiosPrivate = useAxiosPrivate();
const handleSearch = async () => {
const data = JSON.stringify({ from_company: keyWord });
try {
const response = await axiosPrivate.get(SEARCH_URL, data);
console.log(response);
setRecords(response?.data);
} catch (err) {
if (!err?.response) {
console.log("NO SERVER RESPONSE");
} else {
console.log("SOMETHING WRONG");
}
}
};
Server log
{} <-- Prints the request.data as an empty object
"GET /api/find_many/ HTTP/1.1" 200 6276
The django server responses with correct details when I send a request with Postman or Thunder Client. The server also prints the object that were sent with the Postman request. I don't know why the server is unable to get the object or data when I request from my react app.
Request sent from Postman returns
{'from_company': 'Jethmal Paliwal'} <-- Prints the request.data correctly
"GET /api/find_many/ HTTP/1.1" 200 2284
I have double checked everything, my headers are set correctly, Content-Type: application/json, withCredentials: true, and every other possible settings, Even every request from other components works great, but why this particular request doesn't reach the server?
Tried writing the data as an Object in the request funcion itself
const response = axiosPrivate.get(SEARCH_URL, { "from_company": "Jethmal Paliwal" }); which doesn't work as well. The same empty object gets printed.
Tried JSON.stringify the data, which doesn't work as well.
I believe that axios is omitting the data as it's not per REST standard to submit data in the GET request. HTTP allows that, but people and apparently libraries are not expecting it.
This is the API for axios get method:
axios.get(url[, config])
as you see there is no data in the method signature. And if we look at the POST method:
axios.post(url[, data[, config]])
I suggest if you have data to submit to server that you use a POST method instead.

.. from origin .. has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status

I'm fairly new to making API requests. I'm am trying to set up an incoming slack webhook using a simple axios post request from my React project, however I keep receiving the CORS policy error. The request works perfectly in insomnia.
I'm using ngrok to expose my web server running on my local machine to the internet (I assumed this would correct the issue.) So I'm making the request from https://...ngrok.io, however I'm still receiving 'Status Code: 400' in my network tab along with the error above.
axios({
method: "post",
url:
"https://hooks.slack.com/services/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",
headers: { "Content-type": "application/json" },
data: { text: "Hello, World!" },
}).then(
(response) => {
console.log(response);
},
(error) => {
console.log(error);
}
);
};
There are similar errors on stackoverflow, but none fix my error. I'd really like to understand why this is happening so any advice would be appreciated.
Fixed it, for those having the same issue:
What worked for me is setting Content-Type header to application/x-www-form-urlencoded. found it in this thread: https://github.com/axios/axios/issues/475 It appears that this triggers "simple request" and therefore avoids triggering CORS preflight. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests

how to solve 401 error in react native web?

I am trying to make an axios get request but am receiving 401 everytime am trying to fetch. However am already logged in as I have previously received my user login response
My project has been built with react native init and is running on browser using react-native-web.
The same api when I check the response on mobile and postman it is giving the correct response however on browser it is throwing 401
below is my axios code
useEffect(() => {
let url = `${ROOT}/children/${id}/vaccinations`;
axios
.get(url)
.then(function (res) {
console.log("Hello", res);
setData(res.data.content);
})
.catch(function (err) {
console.log(err);
});
}, []);
The response of 3 apis that are being called
The error that am receiving
[![enter image description here][2]][2]
could anyone please tell me where am going wrong?
any help would be appreciated.
[2]: https://i.stack.imgur.com/17Qyf.png
401 code error means you are not authorized, you would need to send your user token that you receive from the backend as a header when sending your specified request, something like that:
axios.get('https://api.github.com/user', {
headers: {
'Authorization': ${access_token}
}
})
You can read more about sending tokens in headers via this link:
https://flaviocopes.com/axios-send-authorization-header/
I hope this helps in solving your issue.

Angular resource not returning error response

I'm having this trouble of handling error responses in AngularJS while using $resource. My setup works perfectly with status 200 responses, but when the API throws out a 400 error I just get an empty object.
This is my controller:
$scope.createProduct = function() {
Api.product.save($scope.product).$promise.then(
function(res) {
console.log(res);
},
function(error) {
console.log(error);
}
)
}
This is my Api service:
function ApiService($resource, API_URL) {
return {
product: $resource(
API_URL + '/product/:product_id', { 'product_id': '#product_id' },
{
show: { method: 'GET' },
update: { method: 'PUT', headers: {'Content-Type': 'application/json'} },
}
),
}
}
This is what console.log(error) prints out after a 400 error:
Object {data: null, status: -1, config: Object, statusText: ""}
And finally this is the error response API spits out which I don't get:
{
"errors": {
"message": [
"The town field is required.",
"The postcode field is required.",
]
}
}
Any help would be appreciated, thanks!
EDIT: As an example try sending a POST request to https://api.twitter.com/1.1/statuses/destroy/1.json. If I do this on Postman, I get this error message:
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
How do I get this response and the string "Bad Authentication data." in Angular? For some reason I can not do this with my current setup.
The issue may relate to interactions between your API server and CORS.
I am running a Flask based API backend that was presenting this same issue. Troubleshooting led me to discovering that my API was performing a TCP RST when receiving the POST request in around 9 out of 10 connections.
Wireshark capture
The Flask server was logging that the response was being sent back correctly.
2018-08-19 13:26:59,104 INFO: 127.0.0.1 - - [19/Aug/2018 13:26:59] "POST /users/test HTTP/1.1" 419]
Cause
The the cause of the issue was rejecting the POST request in the API backend without reading the POST data first. I refactored my API to always read POST data and this solved the problem.
It's not clear to me how CORS effects this situation, however this problem was only seen when making calls through Angular instead of directly to the API.
The following StackOverflow question pointed me in the right direction to solve this.
No response with POST request and Content-Type "application/json" in flask

Resources