Http REST call problems No 'Access-Control-Allow-Origin' on POST - http

I have not been able to get Angular $http to communicate with a remote REST service. I have tried Restangular and $resource too. The problem seems to be with the underlying $http service and CORS limitations. I think I just need to get my headers right. Do I also need to tweak my server config?
I am getting the following error:
XMLHttpRequest cannot load http://www.EXAMPLE-DOMAIN.com/api/v2/users/sign_in. No 'Access-Control- Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
I have researched this a lot. Currently I have tried setting the $httpProvider headings when configuring my app module and played with $http headers. Below is some of my current code.
My Service
app.service('Auth', function($http) {
var headers = {
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'POST, GET, OPTIONS, PUT',
'Content-Type': 'application/json',
'Accept': 'application/json'
};
return $http({
method: "POST",
headers: headers,
url: 'http://www.EXAMPLE-DOMAINcom/api/v2/users/sign_in',
data: {"email":"my#email.com","password":"secret"}
}).success(function(result) {
console.log("Auth.signin.success!")
console.log(result);
}).error(function(data, status, headers, config) {
console.log("Auth.signin.error!")
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
});
});
App Config
var app = angular.module('starter', ['ionic', 'app.controllers', $httpProvider])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.headers.common = 'Content-Type: application/json';
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])

If you are in control of the server, you might need to set the required headers there. Depending on which server, this might help: http://enable-cors.org/server.html

Related

on Nextjs, how to perform a fetch request from an an external public api?

The api is public. Access privallages are to any and everyone.
I've made the same fetch-calls using frameworks such as angular, but on Nextjs I keep running into cors policy errors.
Can someone please explain how I can get the fetch call to work, or provide an example.
I can't fetch from local host as well. There's clearly an error in my practice.
'Access to fetch at '...' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.'
Code example, if helpful:
let fetched =
await fetch('http://127.0.0.1:5001/helloWorld'
, { method: 'GET',
}).then((result)=> console.log('promise complete', result.status));
You need to set mode:'cors'
const response = await fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors',
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
}
});

Firebase HTTP Function triggered twice when POST request sent with headers

I deployed a firebase HTTP cloud function and am experiencing this (unexpected) behavior:
when I call the function (using POST) from a browser environment with fetch(), the function gets triggered twice, one time without any data sent in the body, and another time as I would expect it. In the frontend (chrome network tab) I can only see 1 request, the successfull one.
this does only happen with POST requests
this does only happen when the request is sending headers
Is this normal behavior that I dont understand or a potential bug?
my minimal cloud function
exports.run = functions.https.onRequest(async (req, res) => {
// ALLOW CORS FOR POST REQUEST:
// => https://stackoverflow.com/a/38259193
res.set('Access-Control-Allow-Origin', '*');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
return res.status(200).send({
status: "ok",
body: req.body,
query: req.query,
}).end();
});
calling from frontend
// example data (not a real one)
const url = "https://us-central1-myproject.cloudfunctions.net/test";
const postData = { x: 1, y: 2 };
// GET request => ✅ works as expected
fetch(url);
// POST request without headers => ✅ works as expected
fetch(url, {
method: 'POST',
body: JSON.stringify(postData),
});
// POST request with headers => ❌ 2 requests get triggered
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(postData),
});
This behavior is happening because of the CORS preflight request:
A CORS preflight request is a CORS request that checks to see if the CORS protocol is understood and a server is aware using specific methods and headers.
...
A preflight request is automatically issued by a browser, and in normal cases, front-end developers don't need to craft such requests themselves. It appears when a request is qualified as "to be preflighted" and omitted for simple requests.
As pointed in this other question:
As long as you’re adding a Content-Type': 'application/json' header to the request, the browser is going to automatically on its own do a CORS preflight OPTIONS request before trying the request from your code.
Therefore, this is a normal behavior and is not a problem of Cloud Functions for Firebase.
In order to not have the two requests, you can change the header request as suggested by this answer:
// example data (not a real one)
const url = "https://us-central1-myproject.cloudfunctions.net/test";
const postData = { x: 1, y: 2 };
// POST request with different header => ✅ only one request is triggered
fetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify(postData),
}).then(data => console.log(data));

CORS enabled, but adding cookies in header causes request to be blocked? I have enabled CORS with credentials server side, not sure how to solve this

Using express-session so need cookie id for authentication, but even with setting up CORS correctly (or what I thought to be) on front and back end I'm still getting issues. CORS is working without cookies enabled.
Backend config
const corsOptions = {
origin: "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
preflightContinue: false,
optionsSuccessStatus: 204,
credentials: true,
};
Frontend config (using Relay)
const response = await fetch("http://localhost:4002/graphql", {
method: "POST",
credentials: "include", // Allow cookies to be sent
headers: {
Authorization: `*/*`,
"Content-Type": "application/json",
}
If I do not include credentials the response shows that CORS cookies are allowed:
However, as soon as I enable credentials in the client fetch config, the request is blocked. There is no response, I think Firefox is blocking the req before it is sent?
Thank you in advance for any help!
The issue was not setting the accepted CORS origins to "*", as said in the console (thanks Quentin).

Ionic 3 - Http Get 401 (Unauthorized)

I’m calling a service using a token
Failed to load resource: the server responded with a status of 401 (Unauthorized)
Http failure response for http://localhost:65291/api/post: 401 Unauthorized
The same call works in Postman with Headers;
Content-Type: application/json
Authorization: Bearer token
The function in ionic is
getPosts() {
var header = new HttpHeaders({ "Content-Type": "application/json" });
header.append("Authorization", "Bearer " + this.token);
console.log("Bearer " + this.token);
return new Promise(resolve => {
console.log(this.apiUrl + '/post');
this.http.get(this.apiUrl + '/post', { headers: header}).subscribe((data: Post[]) => {
resolve(data);
}, err => {
console.log(err);
});
});
}
Added a log for the token to be sure that is adding it to the header correctly (the token is fine).
The apiUrl variable has value http://localhost:65291/api.
What is wrong here? Cors is enabled… Postman works ok…
Thanks
I think you definitely have client side problem (since its 401 and also you mention Postman works ok).
I had similar issues when I tried to append headers in the same fashion you did so I would suggest trying this (to eliminate this problem):
getPosts() {
// try forming headers object in one go:
let token = "Bearer "+this.token
let headers = new HttpHeaders({
"Content-Type": "application/json",
"Authorization": token
});
// now here I am not sure why you do promise wrapping this way, but then I would suggest:
return this.http.get(this.apiUrl + '/post', { headers: headers })
.toPromise()
.then((data: Post[]) => { // Success
console.log(data);
resolve(data);
}, (err) => {
console.log(err);
});
}
If the problem is still there - please share which version of Angular and Http module you are using?
Also check out this issue here: How to correctly set Http Request Header in Angular 2
And specifically this answer if you are on Angular 4.3+:
How to correctly set Http Request Header in Angular 2
After a while I found the problem,
header.append("Authorization", "Bearer " + this.token); is wrong. It worked using
let headers = new HttpHeaders({"Authorization: " + "Bearer " + this.token})
Setting multiple headers:
this.http
.post('api/items/add', body, {
headers: new HttpHeaders({
'Authorization': 'my-auth-token',
'x-header': 'x-value'
})
}).subscribe()
I had a similar problem, it works on postman and cors enabled but in the app doesn't work, my problem was i have / at the end of the URL in the API security config, and i was making the request without /, i just remove it from request URL,
also you can add /* in security config or put / in your app, the URL must be the same.
(maybe you have solved your issue and it was different issue but this is a possibe solution)

axios put Not working

my axios code:
const instance = axios.create({
baseURL: process.env.BASE_API,
timeout: 5000,
withCredentials: true,
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
}
})
function get (url, getData) {
return instance.get(url, {
params: getData
})
}
function post (url, postData) {
return instance.post(url, qs.stringify(postData))
}
function put (url, putData) {
return instance.put(url, qs.stringify(putData))
}
export default {
get: get,
post: post,
put: put
}
Post request with content-type': 'application/x-www-form-urlencoded; charset=UTF-8 is useful
However, when using PUT, the request header does not have a content-type': 'application/x-www-form-urlencoded; charset=UTF-8
Causes the put request to become an options
It's not so clear from your question what exactly you are trying to ask. I'll assume you want your PUT request to actually send a PUT request instead of just an OPTIONS request. I'm also assuming that you are making requests to an API that you control.
I had the same problem (i.e. I was only seeing OPTIONS requests when I tried to make PUT calls) and I discovered that in my API I did not have the PUT options enabled in my CORS settings. I'm using rails so all I had to do is add :put to my cors middleware:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :put, :options]
end
end
I figured this out based on this answer

Resources