I have seen many answers in stack overflow which says setting response headers will make you "CORS" request.But no solution worked for me.I have written the following code:
//Server.js Code
var express = require('express'),
app = express();
app.all('*',function(req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
next();
I am trying to access the content from the URL using $http in client side:
//Controller.js
$http.get('http://domainA.com/a/ipadapi.php?id=135&client=ipad').success(function(response){
alert("I got response");
});
It's showing the following error in console.
XMLHttpRequest cannot load http://domainA.com/a/ipadapi.php?id=135&client=ipad The 'Access-Control-Allow-Origin' header has a value 'http://example.xxxxx.com' that is not equal to the supplied origin. Origin 'http://localhost:3000' is therefore not allowed access.
Note:I am new to nodeJS,Express and AngularJs
When you are passing credentials with CORS, you need to lock down the accepted origins. Try changing your origins from * to "localhost:3000"
See cross origin resource sharing with credentials
Change the header info from
res.setHeader("Access-Control-Allow-Origin", "*");
TO
res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
If you're not the owner of domainA then you cannot send CORS headers from that domain. You can use your Node server as middleware, and proxy the request from your server to domainA. Your server can send CORS headers back to your angular app. pseudo code with hapi and needle:
import Hapi from 'hapi'
import needle from 'needle'
const server = new Hapi.Server()
server.connection({
port: 9090
, routes: {
cors: true
}
})
const handler = (req, reply) => {
const url = 'https://domainA.com'
, data = {
body: 'code'
}
needle.post(url, 'body=${data.body}', function(err, res) {
let json = JSON.parse(res.body)
reply(json.data)
})
}
server.route({
method: 'GET',
path: '/route/{id}',
handler: handler
}
)
server.start( err => {
if( err ) {
console.error( 'Error was handled!' )
console.error( err )
}
console.log( 'Server started at ${ server.info.uri }' )
})
Related
As a starter, I have read a bunch of question concerning the same issue.
When I open the connection with the socket via React client the normal way, just the URL as parameter, I don't get this error, connection established.
But when I do this:
const io = ioClient(webSocketUrl, {
transportOptions: {
polling: {
extraHeaders: getAuthenticationToken()
}
}
});
The request return a CORS error everytime.
I have tried to:
Set the origin like so: io.origins(['*:*']);
app.use(function (req, res, next) {
res.setHeader(
"Access-Control-Allow-Origin",
req.header("origin") ||
req.header("x-forwarded-host") ||
req.header("referer") ||
req.header("host")
);
res.header(
"Access-Control-Allow-Methods",
"GET, POST, OPTIONS, PUT, PATCH, DELETE"
);
res.header("Access-Control-Allow-Headers", "X-Requested-With,content-type");
res.setHeader("Access-Control-Allow-Credentials", false);
next();
});
And also this:
app.use(cors());
app.options("*", cors());
None of the above worked.
I would appreciate any help.
Found the answer!
For anyone with the same problem, this is how I've done it:
const io = require("socket.io")(server, {
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin, //or the specific origin you want to give access to,
"Access-Control-Allow-Credentials": true
};
res.writeHead(200, headers);
res.end();
}
});
I am trying to make the frontend (React JS) work with my backend server (Express JS). I am still fighting with CORS. The frontend requests are still blocked by CORS.
According to CORS documentation I have set my Express instance to use cors() as middleware:
const app = express();
// Middlewares
const whitelist = [
'http://localhost:3000',
'http://localhost:3001'
];
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
};
app.use(cors(corsOptions));
If someone asks why am I using CORS with localhost at all, is because I was told to do so since I had to send withCredentials: true header from axios requests to persist session after login.
I just added axios.defaults.withCredentials = true to intercept requests in the frontend.
The way it was working before adding more domains to corsOptions was setting up a middlewares to let the server work with the frontend:
export const setHeaders = (req, res, next) => {
res.header('Access-Control-Allow-Origin', process.env.APP_URL);
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
};
...
app.use(setHeaders);
If I remove the previous code, it won't work even for one domain.
So, what I have to change in order to let the server fetch data from multiple domains? Thanks in advance.
Add credentials and allowedHeaders options to your corsOptions config
credentials: true,
allowedHeaders: ['Origin, X-Requested-With, Content-Type, Accept'],
Read https://www.npmjs.com/package/cors#configuration-options
Also, you can whitelist domains with 127.0.0.1 as you might want to access them via localhost or 127.0.0.1
Full code
const app = express();
// Middlewares
const whitelist = [
'http://localhost:3000',
'http://127.0.0.1:3000'.
'http://localhost:3001',
'http://127.0.0.1:3001',
];
const corsOptions = {
credentials: true,
allowedHeaders: ['Origin, X-Requested-With, Content-Type, Accept'],
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
}
};
app.use(cors(corsOptions));
I have a node.js app and am developing a separate single page app (that will eventually be converted into Android and iOS native apps). I'm setting up an API on the node.js app and am struggling with authentication. The node.js app is using passport-local-mongoose for authentication and I store user data in a MongoDB backend. For testing/dev, the single page app is running on http://localhost:1234/.
My endpoint looks like:
exports.getDevicesAPI = async (req, res) => {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers: Authorization');
const devices = await Device.find({ owner: req.user._id });
res.json(devices);
};
I can GET this no problem with something like:
const axios = require('axios');
const url = 'http://localhost:7777/api/devices';
function getDevices() {
axios
.get(url)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
}
I want to add authenticate = passport.authenticate('header', {session: false, failWithError: true}); on the server side to provide authentication, but the following gives me Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:7777/api/devices. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing):
const axios = require('axios');
const url = 'http://localhost:7777/api/devices';
const username = myUsername;
const password = myPassword;
const axiosConfig = {
headers: {
'Content-Type': 'application/json',
},
Authorization: {
username,
password,
},
};
function authenticate() {
axios
.post(url, axiosConfig)
.then(function(response) {
console.log('Authenticated');
})
.catch(function(error) {
console.log('Error on Authentication');
});
}
Routes (for testing):
router.get('/api/devices', catchErrors(deviceController.getDevicesAPI));
router.post('/api/devices', catchErrors(deviceController.getDevicesAPI));
What am I missing?
You are having issues with CORS(Cross-Origin Resource Sharing) Restrictions. Read more about CORS here.
I believe this part of your code is meant to handle the CORS:
exports.getDevicesAPI = async (req, res) => {
// ...
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers: Authorization');
// ...
};
However, the mistake here is that the setting of these CORS headers is tied to a route, i.e the getDevicesAPI route which is not supposed to be. For requests that are likely to modify resources in another origin(e.g the POST to getDevicesAPI route), the browser would first send a preflight request with the OPTIONS Http method before sending the actual request, the response to the preflight request is where the necessary CORS response-headers is expected to be set. You can find explanations on preflight requests here.
I would typically add a middleware like this above the other routes:
router.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', '*');
next();
});
I would use Socket.IO . I have read the official documentation and tried to do the same thing so I create my server :
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require("express"); // call express
var app = express();
var bodyParser = require("body-parser");
// define our app using express
var routerProj = require("./routes/ajoutProj");
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;
mongoose.connect("mongodb://localhost:27017", {
useMongoClient: true
/* other options */
}); // connect to our database
mongoose.connection.on("error", function(error) {
console.log("error", error);
});
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT ,DELETE");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/api/proj", routerProj);
app.get("/", function(req, res) {
res.sendFile(__dirname + "../src/index.html");
});
// Chargement de socket.io
// Quand un client se connecte, on le note dans la console
io.sockets.on("connection", function(socket) {
console.log("User is coonected!");
});
var port = process.env.PORT || 8081; // set our port
// START THE SERVER
// =============================================================================
var server = app.listen(port);
var io = require("socket.io").listen(server);
My angular index.htlm file is in this path relatively to server.js : ../src/app/index.html
When I restart server and angular app, then open new window I don't have a message on the servers's console telling me that a user is connected knowing that angular is making calls to the server api
I don't know where is the problem
Update
I have added socket.IO on client side
import { Injectable } from "#angular/core";
import { NouveauProjet } from "./models/nouveau-projet";
import { HttpClient, HttpResponse } from "#angular/common/http";
import { Observable } from "rxjs/Observable";
import "rxjs/add/operator/map";
import "rxjs/add/operator/catch";
import * as io from "socket.io-client";
#Injectable()
export class AjoutprojService {
apiURL = "http://127.0.0.1:8080/api/proj/projets";
private socket = io("http://localhost:8081");
constructor(private http: HttpClient) {}
getAllProj(): Observable<NouveauProjet[]> {
return this.http.get<NouveauProjet[]>(
"http://127.0.0.1:8081/api/proj/projets"
);
}
getProj(id): Observable<NouveauProjet[]> {
return this.http.get<NouveauProjet[]>(
"http://127.0.0.1:8081/api/proj/nouvProjs/${id}"
);
}
addProj(nouveauProjet: NouveauProjet): Observable<any> {
return this.http.post<NouveauProjet[]>(
"http://127.0.0.1:8081/api/proj/projets",
nouveauProjet
);
}
}
/* private handleError ( response: HttpResponse): Observable<any> {
let errorMessage= `${response.status} - ${response.statusText}`;
return Observable.throw(errorMessage);
}*/
Restarted server , client , no result
Update 2
after adding socket.on('event', function(evt){ console.log(evt); });I get those errors :
Failed to load http://localhost:8081/socket.io/?EIO=3&transport=polling&t=M2tXQXh: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
GET http://localhost:8081/socket.io/?EIO=3&transport=polling&t=M2tXQXh 404 (Not Found)
If I set res.header("Access-Control-Allow-Origin", "*"); To res.header("Access-Control-Allow-Origin", "http://localhost:4200");
I get this error
Failed to load http://localhost:8081/socket.io/?EIO=3&transport=polling&t=M2uichH: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://localhost:4200' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
I notice a difference in the error . Here The value of the 'Access-Control-Allow-Credentials' header in the response is ''
When I put localhost:8081 : The value of the 'Access-Control-Allow-Credentials' header in the response is 'localhost:8081'
Based on the error, I suspect the problem is that you are using a wildcard in your server's CORS response header:
res.header("Access-Control-Allow-Origin", "*");
Why is this a problem? From the docs:
When responding to a credentialed request, the server must specify an origin in the value of the Access-Control-Allow-Origin header, instead of specifying the "*" wildcard.
Here is a relevant StackOverflow answer:
This is a part of security, you cannot do that. If you want to allow credentials then your Access-Control-Allow-Origin must not use *. You will have to specify the exact protocol + domain + port.
This question already has answers here:
Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
(36 answers)
Closed 7 years ago.
Having issues getting data back from a http post request to an API I've been building. Throws the error:
XMLHttpRequest cannot load (URL to API here). No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:9000' is therefore not allowed
access.
Here's the Angular code on the client side:
$http.post('MyAPIsURLHere', {
date: $scope.information.PubDate
})
.then(console.log)
.catch(console.error);
And here's the Node server side code for my API:
app.post('/getThing', (req, res) => {
const date = req.body.date;
const query = Overquery
const query2 = "alter session set nls_date_format = 'MM/dd/yyyy'";
oracleDB.execute(query2, (err, result) => {
if(err) {
console.error(err);
}
else {
console.log(result);
}
});
oracleDB.execute(query, (err, result) => {
if(err) {
console.error(err);
}
else {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'POST');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.json(result.rows);
}
});
});
First time building an API so any suggestions and help would be greatly appreciated!
Run the following in your project from a bash shell:
npm install cors --save
It will install this:
https://github.com/expressjs/cors
Then add this to your server when creating the app.
var express = require('express');
var cors = require('cors');
var app = express();
app.use(cors());
Edit: This will enable CORS for every domain wich is not recomended for security reasons. Check here for further CORS configuration: https://github.com/expressjs/cors#configuring-cors
In your node application, this sample of code should solve your issues:
// Allowing X-domain request
var allowCrossDomain = function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Cache-Control");
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(allowCrossDomain);