I'm trying to use Axios in node like I would use something like CURL. I am making an api request to my node endpoint. I then use Axios to make a request to Spotify to do some OAuth stuff. I get the response back from the Axios request successfully but when I try and return a response in Express I am told the headers have already been sent. Below is a test I have set up to isolate the issue. This give the error "Can't set headers after they are sent".
makeRequest: function(req, res, next) {
axios.get('https://google.com')
.then(function(){
res.status(200).send({});
});
}
Can this be done? Thanks.
I think because I was modifying the headers of every request it was causing some problems, e.g.
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH');
I used a different router for the requests that I use Axios and it works OK now. Something like:
app.use('/api', apiRouter);
app.use('/callback', axiosRouter);
apiRouter.use(function(req, res, next) {
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH');
}
//I don't modify the axiosRouter headers
Related
I'm trying to send a http post request from my angular app to my node.js server with user credentials in order to log it.
Both are hosted in IIS (the node server with nodeiis) and both are configured to be authenticated by windows authentication.
My angular code:
var url = "http://myurl:15001/addItem";
this.http.post(url, {
"itemName": "SomeName",
"itemColor": "SomeColor"
}, {withCredentials: true}).subscribe(res =>{
console.log("Great, item was added");
})
My Node.js Code:
var app = express();
var allowCrossDomain = function (req, res, next){
res.header('Access-Control-Allow-Origin', "http://myurl") //Cannot be a wildcard because of the credentials.
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
if(res.method == 'OPTIONS')
res.send(200);
else
next();
};
app.use(allowCrossDomain);
app.post('/addItem', function(req, res){
//Saves the item...
res.setHeader('Access-Control-Allow-Origin', 'http://myurl')
res.status(200);
res.send(true);
});
When I do the request I get the following error to the console:
OPTIONS http://myurl:15001/addItem 401(Unauthorized)
XMLHttpRequest cannot load http://myurl:15001/addItem. Response to
preflight doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://myurl' is therefore bot allowed access. The
response had HTTP status code 401.
When I try to do the same thing with my http get request everything works properly and I get the result.
I don't know why my OPTIONS request is unauthorized when I send 200 code for every OPTIONS request.
I tried to use cors node.js package but it didn't help, maybe I didn't used that right.
Could someone explain me how can I solve this and make my http post pass the preflight? Thanks a lot!
If you are using Angular 6, it supports proxy.conf which will proxy the Backend API URL. For more details, here is the link https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md
No matter what I try to use to set the headers it simply won't work.
The server side needs to send the response headers like this, after accepting the POST request from Frontend.
server.js
app.post('/register', (req, res) => {
res.set({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.send('string');
res.end();
}
The res.set() function was not the only function I tried to use.
I tried with:
res.writeHead(201, {'Access-Control-Allow-Origin': '*'}) - doesn't work
res.setHeader('Access-Control-Allow-Origin', '*') - nope
res.headers() - also doesn't work
It says here that it goes like this: How can I set response header on express.js assets but the answer doesn't work for me.
No matter what I tried, the server just won't respond with the CORS enabled header and I need that header property. What am I doing wrong?
Try using the cors module: https://www.npmjs.com/package/cors
var cors = require('cors')
...
app.use(cors())
The Access-Control-Expose-Headers response header indicates which headers can be exposed as part of the response by listing their names.
You can read more about it here: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
res.set('Access-Control-Expose-Headers', 'Access-Control-Allow-Origin, <any-other-custom-header>, ...');
I have a site that is using Passport Steam Strategy. My server (Node with Express) is currently running on localhost:3000 while my front end is running on localhost:8080. I keep running into a cross-origin issue, only when attempting to authorize through Steam. My requests are made through Axios and I am using CORS. I've spent hours Googling and trying various things but I can't seem to get it to work.
This is the error that I get:
XMLHttpRequest cannot load
https://steamcommunity.com/openid/login?openid.mode=checkid_setup&openid.ns…3000%2Fsteam%2Fauth%2Freturn&openid.realm=http%3A%2F%2Flocalhost%3A3000%2F.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
Here is where the route is called from the front end:
linkSteam(){
api('http://localhost:3000/steam/auth')
.then(res => {
console.log(res);
state.user = res.data.user;
})
}
And here is my axios configuration on the front end.
let api = axios.create({
baseURL: 'http://localhost:3000/api/',
timeout: 3000,
withCredentials: true
})
My CORS is set up as follows
var whitelist = ['http://localhost:8080', 'https://steamcommunity.com', 'http://localhost:3000', 'null'];
// I added null here as someone said that it worked as their origin displayed null like mine does
var corsOptions = {
origin: function (origin, callback) {
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
},
credentials: true
};
I then import my CORS into my main file and use it as follows
app.use(cors(corsOptions))
app.use('*', cors(corsOptions))
I kept seeing that you can set your Access-Control-Allow-Credentials, etc and did so
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
});
This didn't help. I've tried breaking down my original function where /steam/auth is called and running a console.log(req.headers.origin) and spits back my correct URL, but then the error still reports that the Origin is null. If I set my Access-Control-Allow-Origin' to '*', I get a slightly different error that I must provide credentials, and that the Origin 'localhost:8080' is therefore not allowed.
Here's my /steam/auth route.
router.get('/steam/auth',
passport.authenticate('steam', {
failureRedirect: '/'
}),
function (req, res) {
res.redirect('/');
});
And this does work if I click on the URL that cannot be loaded and then login to Steam. It will then redirect me back to my site with my Steam profile information intact. The error is on attempting to get the initial redirect back to Steam in order to login. I have also tried doing this in a res.redirect to their direct URL and I get the same error.
Thanks in advance for any help! And let me know if I'm missing vital information. I've tried to include everything, but I wouldn't be surprise if I missed something.
If the error message in the question is the actual message the browser is reporting, it’s because your client-side code is trying to send a request to https://steamcommunity.com/openid/login.
So given that, no matter what config changes you make to your Node server on localhost:3000, that’s not going to change anything. Instead it seems like you you need to figure out where your client-side code is sending a request to https://steamcommunity.com/openid/login and why.
And the reason the request to https://steamcommunity.com/openid/login fails is that server doesn’t include the Access-Control-Allow-Origin response header in its response.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has more details.
So because you can’t change the server’s behaviour, your browser will continue so block your code from getting at the response as long as it lacks the Access-Control-Allow-Origin header.
I don’t know how authorization is handled by Steam but maybe you instead need to either make the authorization request to Steam through your existing Node backend somehow, or else set up your own CORS proxy using, e.g., https://github.com/Rob--W/cors-anywhere/, and proxy your client-side authorization request to Steam through it.
I am using express 4.1.0, and angular 1.2.12.
My client-code looks like this:
$http.get(data_url + '/stickers.json')
.success(function (data, status, headers, config) {
// do stuff
})
.error(function (data, status, headers, config) {
console.log(status, config);
});
I have done all the correct express stuff, as far as I can tell:
var express = require('express'),
app = express();
app.use(function (req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
res.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.set('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Accept');
next();
});
app.use(express.static(__dirname + '/webroot'));
app.listen(process.env.PORT || 5000);
I also tried cors module.
I am running my client-app on localhost, port 8000. The remote file is on heroku.
In all cases, I get this error in the console:
XMLHttpRequest cannot load http://<URL>/stickers.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access.
When I access http://<URL>/stickers.json directly and look at returned headers, I see these:
Access-Control-Allow-Headers:X-Requested-With,content-type
Access-Control-Allow-Methods:GET, POST, OPTIONS, PUT, PATCH, DELETE
Access-Control-Allow-Origin:*
Update:
If you'd like to look at it, I made a codepen, and a new heroku app with above server code.
Weirdly, it works fine, so now I am really confused. I think it must be express, because it stops working when I swap the URLs.
Update 2:
If I run the codepen with the URL from localhost running the original code, it also works. It must be something funny with heroku.
I got it! it needs to be http://*.herokuapp.com/, or it redirects. I was using *.heroku.com.
I'm in the process of writing a simple library application to get ready for a larger project with AngularJS. After reading a lot online about using $resource to interact with a RESTful API, I decided that it would probably offer some time-saving and scaling benefits to implement it instead of using $http for each request. The problem is that for some reason (I'm no expert on CORS and the request is being sent cross-domain) when using the $save method my Node.js console shows:
OPTIONS /books 200 1ms - 161b
Using the query() method works fine - the Node console shows:
GET /books 200 1ms - 228b
I've been stuck for several hours at this point, trying variations on the below but it always ends up being an OPTIONS request instead of POST (which is what it should be according to the Angular documentation) for the $save method.
AngularJS Web App
app.js
var libraryApp = angular.module('libraryApp', ['ngResource', 'ngRoute', 'libraryControllers']);
libraryApp.factory('$book', ['$resource', function ($resource) {
return $resource('http://mywebserver\\:1337/books/:bookId', { bookId: '#bookId' });
}]);
controllers.js
var libraryControllers = angular.module('libraryControllers', []);
libraryControllers.controller('BookCtrl', ['$scope', '$book', function($scope, $book) {
...
$scope.addBook = function () {
var b = new $book;
b.isbn = "TEST";
b.description = "TEST";
b.price = 9.99;
b.$save();
};
}]);
Node.js with Express REST API
app.js
var express = require('express'),
books = require('./routes/books'),
http = require('http'),
path = require('path');
var app = express();
...
// enable cross-domain scripting
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", req.headers.origin);
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// routing
app.get('/books', books.getAll);
app.get('/books/:isbn', books.get);
// This is what I want to fire with the $save method
app.post('/books', books.add);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
./routes/books.js
...
exports.add = function(req, res) {
console.log("POST request received...");
console.log(req.body.isbn);
};
Tried putting this line in my config function delete $httpProvider.defaults.headers.common["X-Requested-With"]; but no change.
I'm no Angular/Node pro but right now I'm thinking that it's something to do with it being cross domain and, like I said, I'm no expert on CORS.
Thanks in advance.
I know it may be in bad taste to answer my own question but I figured out the problem a few days after posting this.
It all comes down to how browsers manage CORS. When making a cross-domain request in JavaScript that is not "simple" (i.e. a GET request - which explains why the query() function worked), the browser will automatically make a HTTP OPTIONS request to the specified URL/URI, called a "pre-flight" request or "promise". As long as the remote source returns a HTTP status code of 200 and relevant details about what it will accept in the response headers, then the browser will go ahead with the original JavaScript call.
Here's a brief jQuery example:
function makeRequest() {
// browser makes HTTP OPTIONS request to www.myotherwebsite.com/api/test
// and if it receives a HTTP status code of 200 and relevant details about
// what it will accept in HTTP headers, then it will make this POST request...
$.post( "www.myotherwebsite.com/api/test", function(data) {
alert(data);
});
// ...if not then it won't - it's that simple.
}
All I had to do was add the details of what the server will accept in the response headers:
// apply this rule to all requests accessing any URL/URI
app.all('*', function(req, res, next) {
// add details of what is allowed in HTTP request headers to the response headers
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
res.header('Access-Control-Allow-Credentials', false);
res.header('Access-Control-Max-Age', '86400');
res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
// the next() function continues execution and will move onto the requested URL/URI
next();
});
And then insert these few lines before the Express routing to simply return a HTTP 200 status code for every OPTIONS request:
// fulfils pre-flight/promise request
app.options('*', function(req, res) {
res.send(200);
});
Hopefully this will help anyone who stumbles on this page suffering from the same problem.
I didn´t actually try this, but wouldn´t it be enough to tell the Ressource how to handle the $save request?
$resource('http://mywebserver\\:1337/books/:bookId', { bookId: '#bookId' }, {save: {method: 'POST'});