axios returns 500 while postman returns 200 - reactjs

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.

Related

How to retrieve Authorization header (rails / react app)

Im banging my head and cant solve the mystery :(.
I've rails app and react, rails app returns Authorization bearer token in response header and also it returns Access-Control-Expose-Headers: Authorization
I see in the responses that everything is returned properly, but when I try to get value of Authorization header using response.headers.get('Authorization') Im getting null
My Fetch looks like:
fetch('/users/sign_in.json', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'X-CSRF-Token': token},
body: JSON.stringify({ user: values })
})
.then((response) => console.log(response.headers.get('Authorization')))
.then((data) => console.log(data))
What Im missing?
Ive checked cookies - rails does not save token into cookie, Im using devise-jwt gem. Thanks for any hint.
Problem solved...
When user signs in, in first response he gets Authorization header. I've tried sign in already signed user, and I'didnt get any proper header although in chrome debugger Authorization header was present in response :/

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

http post request in reactjs not working

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

Authentication Error when using mode: no-cors using fetch in React

I am building a React app that is pulling different stats from services for our internal developers (commits, tracked hours, etc)..
I am using fetch to grab API data from Harvest, a time tracking app. According to their docs, you can use basic HTTP authentication. When I use the app Postman, all is well and I can see the response just fine. Initially I used:
getHarvest(){
// Set Harvest Headers
const harvestHeaders = {
method: 'GET',
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxx=',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache',
}
};
fetch('https://factor1.harvestapp.com/projects/', harvestHeaders)
.then( response => response.json() )
.then( projects => {
// Do some stuff
} )
}
This gives me an error in the console:
Fetch API cannot load https://myaccount.harvestapp.com/projects/.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:3000' is therefore not allowed
access. The response had HTTP status code 404. If an opaque response
serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.
So with that feedback I changed the function to look like this:
getHarvest(){
// Set Harvest Headers
const harvestHeaders = {
method: 'GET',
mode: 'no-cors',
headers: {
'Authorization': 'Basic xxxxxxxxxxxxxxx=',
'Content-Type': 'application/json',
'Accept': 'application/json',
'Cache-Control': 'no-cache',
}
};
fetch('https://factor1.harvestapp.com/projects/', harvestHeaders)
.then( response => response.json() )
.then( projects => {
// do stuff
} )
}
But that results in an Authentication error:
GET https://myaccount.harvestapp.com/projects/ 401 (Unauthorized)
I'm not sure how I can get the response correctly. Am I doing something wrong? It seems odd to me that using the app Postman works but this doesn't. Thoughts? Thanks!
It doesn’t seem like the Harvest API is meant to be used with XHR or Fetch from Web applications.
At least their docs don’t mention anything about using their API from XHR or Fetch, nor do those docs mention anything about Access-Control-Allow-Origin nor CORS in general.
Instead the docs give examples of using the API with curl and with the Postman REST Client.
And trying examples in the docs like below, the response has no Access-Control-Allow-Origin.
curl -H 'Content-Type: application/xml' -H 'Accept: application/xml' \
-u "user#example.com:password" https://example.harvestapp.com/account/who_am_i
So it seems like the answer is: You can’t access the Harvest API with XHR/Fetch from a Web app.
It works in Postman because Postman is not bound by the same-origin policy browsers enforce to prevent Web apps running in a browser from making cross-origin requests unless the site/endpoint the request is made to has opted in to using CORS (which it seems Harvest hasn’t opted into).

Resources