http post request in reactjs not working - reactjs

I am trying to make a http post request from my reactjs application to express that locally hosted as well. I dont need to pass anything from this post request (no params needed), i just want the request to go through. All params have been specified in my express code. I am running my reactjs application locally in a different port. Here is how i am doing it.
fetch('http://localhost:8080/api/send', { 'mode': 'no-cors' }, {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: {
}
});
This link works on the postman, just this http post method isn't working. Any help would be appreciated.

For me, it is working when I remove ,
{ 'mode': 'no-cors' }
Also, assuming you're body: has content (it's empty right now so therefore wouldnt do anything on a POST request): you should add JSON.stringify() to the body. So:
body: JSON.stringify({
//content here
})
If cors is giving you issues, there's an easy way to fix that on the back end (specifically with rails).

Related

API cs-cart put request by react and axios

I use react in front-end and cs-cart API in back-end.
In the following code I used axios.put() as follows:
const data = JSON.stringify({
"test1": "val1"
});
const config = {
method: 'put',
url: 'https://example.com/api/product/111',
headers: {
'Authorization': `Basic ${token}`,
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(res => {
console.log(res)
});
When sending a request, the browser sends a request with the OPTIONS method, which error: 405
Method Not Allowed returns.
And the original request (PUT) is not sent.
cs-cart is installed on the server. And the react project on localhost
Have you made sure to understand the error correctly i.e
The HyperText Transfer Protocol (HTTP) 405 Method Not Allowed response
status code indicates that the server knows the request method, but
the target resource doesnt support this method.
The server must generate an Allow header field in a 405 status code
response. The field must contain a list of methods that the target
resource currently supports.
Make sure that the server is able to understand how to interpret your request so the clients are able to proceed.
You can look at this in more detail below here.

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

axios returns 500 while postman returns 200

I am trying to call an api using axios but the problem is that it keeps returning 500 while postman is returning 200.
I've tried using fetch too but the result didn't change.
Here's my code and i hope you can help me out on this one.
and also i'm using a proxy in my package.json to get past the CORS erros.
let headers = {
'Authorization': 'a',
'Accept': 'application/json'
}
axios.get("v1/index-items", { headers: headers })
.then(res => {
console.log(res)
})
The problem can be in two things: wrong request URL, or CORS problems. In the second case, you need to configure CORS on your backend. Try to look at the headers on the response, are all needed headers there? Try to look in the developer console, there should be CORS error.

React - fetching from API, how to skip the cors response

I want to make a simple POST request from my React app to my Spring back-end to authenticate the user. What i am doing :
fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({
username: this.state.username,
password: this.state.password,
}),
})
.then(response => response.json()).then(resposne => console.log(resposne))
Trying to make this call will get me a SyntaxError: Unexpected end of JSON input. If i log the response i can see that it is a response with a type:cors. I assume i am getting the response from the OPTIONS request that goes out. How can i skip that response? If i check the headers on the response, the header that i want to get, which is the Authorization header, is non-existant. If i go to chrome devtools - network section, and look at the response i am getting, i can see the resposne is as it should be, and i can even see the token returned in the Authorization header. How can i access that header in my React app? Server is properly configured since it returns the token, i just cant get it in the React app.
Thanks!
You should add the Access Control Expose Headers with the Authorization header like so:
Access-Control-Expose-Headers: Authorization
It doesn't seems an error on the token generation. Did you take a look on Response body?
Seems like the response body is not a valid json.

ReactJS seems to turn POST requests into GET requests

I'm using React and the fetch API to do a POST request to a user authentication backend. I can do this POST request below with Postman, and I get the correct JWT back, but oddly - whenever I use the following code in React, the POST request somehow hits the server as a GET request.
Code in React:
return this.fetch('http://fakeURL.com/auth', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
"email": "email#email.com",
"password": "password",
})
}).then(res => {
this.setToken(res.token);
return Promise.resolve(res);
})
The logs show (first the pre-flight request):
Request URL: http://fakeURL.com/auth
Request Method: OPTIONS
Status Code: 200 OK
Referrer Policy: no-referrer-when-downgrade
And the actual request:
Request URL: http://fakeURL.com/auth
Request Method: GET
Status Code: 405 METHOD NOT ALLOWED
Referrer Policy: no-referrer-when-downgrade
Things I've tried:
Running the app both locally and in an AWS S3 bucket (with CORS configured to allow all methods, and from any origin)
Using Flask on our backend to enable CORS
Hitting our backend via Postman with the same API POST request (when we use Postman, the API request works as intended, as a POST that returns a token)
Hitting other URLs (e.g. http://httpbin.org/post) to see if my code can hit those endpoints with a POST rather than a GET... and those endpoints see GET requests as well (instead of the intended POST)
This is so confusing - what could possibly cause our POST request to go out as a GET request? I feel like we've eliminated every possibly cause outside of something weird happening in React. Thanks for the help!
npm install --save axios
on your auth page:
import axios from 'axios'
Modify your post so instead of using fetch:
login(emailValue, passwordValue) {
return axios({
url: `yourAuthURL`,
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
data: {
"email": emailValue,
"password": passwordValue,
}
}).then(res => {
console.log(res);
})
}

Resources