http get request in angularjs converts to option request - angularjs

When sending request with header in angulajs. The request is:
$http.get('http://dev.oms.fetchr.us/order/',{
headers:{
'Authorization': 'Token ' + token
}
})
The request is converted to option request. If I remove the authorization token it works as get request, but returns 403 error.
After so much time and reading I got this about preflight requests.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Server-Side_Access_Control
I also tried with adding headers define here. But results gives error.
If I edit the request in mozilla console and resend the request then it works. And I am able to hit the api.
I also tried this: How does Access-Control-Allow-Origin header work?
to allow origin.but as i running on local server.It is not working too.
It is working fine in JQuery. But not with angularjs please help how to send get request in angularjs with express server on cross-origin.

For making get request with header use this
$http({
"method": "GET",
"url": url + "",
"data": '',
"headers": { 'Authorization': Your Token },
"Content-Type": "application/x-www-form-urlencoded ; charset=UTF-8"
})

Related

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

IE Edge Angular JS $http post CORS request JSON not working

I am working on Angular JS app which connects to CORS .NET WEB API. The below code works fine with chrome / firefox / safari browsers but for some reason not on IE Edge (any version). I get OPTIONS pre-flight response with HTTP code 200 but subsequent post request does NOT fire.
var postData = {
'id': 1,
'name':'Niket'
}
function SendData(APIServiceUrl, postData)
{
return $http({
method: 'POST',
url: URL + APIServiceUrl,
data: postData,
headers: { 'Content-Type': 'application/json; charset=UTF-8' }
});
}
If I switch the content-type to
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
then I do get the post request working. But our API Server response only allows
Access-Control-Allow-Headers: Authorization, Content-Type
I have gone through dozens sites to solve this issue, and have tried bunch of solutions ranging from JSON.stringify(), verifying caching is disabled, syntax checking, CORS setup etc. but not able to find solution to why the POST request does NOT fire in IE Edge.
An article that I have found along similar line is this but that has not been SOLVED either --> Post JSON ajax request with cors not working in IE10/Edge.
Angular JS ver 1.5.7, IE Edge version 40.15063.0.0,
PLEASE HELP!!!

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

Angular JS - $http not sending headers

As the title suggest, I need to pass an authorization token but when I check the network console, I'm getting a 403 because the accept and authorization isn't there. NOTE: I removed my authorization token for this example
$http({
url: 'http://api.stubhub.com/search/catalog/events/v2?title="san"',
dataType: 'json',
method: 'GET',
data: '',
headers: {
"Content-Type": 'application/json',
"Authorization": 'Bearer {token}'
}
}).success(function(response){
$scope.searchResponse = response;
}).error(function(error){
$scope.error = error;
});
This seems like correct syntax? What's wrong here?
EDIT: added the XHR screenshot
EDIT: 2. Here's my network traffic, HAR via paste bin:
http://pastebin.com/fiFngZSy
setting custom headers on XHR requests triggers a preflight request.
I bet you're seeing an OPTIONS request without the Authorization header, and a corresponding response whose Access-Control-Allow-Headers header value is not listing Authorization, or the API doesn't even allow unauthorized OPTIONS requests.
I don't know the stubhub api, but does it return CORS-compliant responses?

Resources