How to set access control allow origin in socket io - javascript

I am using socket.io and express js. I want to set access control allow origin to the socket connection
I've tried setting the origins property when initializing socket
var io = require('socket.io')(http, {origins: 'http://www.example.com'})
In the image above access control allow origin is set to *. I want to set that to example.com (also note the request method is GET)
In this image however the access control allow origin header is set (also note the request method is POST)
How can I add the access control allow origin header when the request method is GET. Please help

Have you tried:
io.set('origins', 'http://yourdomain.com:80');
Or you can also try server.origins like below:
io.origins((origin, callback) => {
if (origin !== 'https://foo.example.com') {
return callback('origin not allowed', false);
}
callback(null, true);
});
By returning true, you allow the origin. Otherwise, send the error message. Refer docs here

please try below in express main file
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://yourdomain.com:80');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Pass to next layer of middleware
next();
});

In Express you can use like this:
app.all('*(or set for what way you exectly need)', function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', 'http://www.example.com');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'your headers');
next();
});
Also in the socket.io you do not need to specify separately headers for POST or GET... this is a different communication protocol.
Here is example for socket set you can try:
io.set( 'origins', '*www.example.com' );

Access-Control-Allow-Origin: http://example.com
Access-Control-Allow-Methods: GET
Access-Control-Allow-Headers: Content-Type

Related

Cross-Origin Request Blocked with React and Express

So I hit this error, when I was trying to send data to the back end using React. From what I learnt I need to allow the communication on the back-end and in the .htaccess file. Here are some of the links I used:
No 'Access-Control-Allow-Origin' - Node / Apache Port Issue
How does Access-Control-Allow-Origin header work?
Both of them have code, but it didn't help.
So far my Server-side code is this:
app.use(function (req, res, next) {
// Website you wish to allow to connect
// res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'POST');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
This is my Client-side code:
sendMail(e) {
e.preventDefault();
var name = document.getElementById('name').value;
var contactReason = document.getElementById('contactReason').value;
var email = document.getElementById('email').value;
var additionalInfo = document.getElementById('additionalInfo').value;
var body = {
name: name,
contactReason: contactReason,
email: email,
additionalInfo: additionalInfo,
};
console.log(JSON.stringify(body));
fetch('http://localhost:4000/', {
method: 'POST',
body: body,
}).then(r => console.log(r)).catch(e => console.log(e));
}
So what am I missing? I do not have an .htaccess file, but I'm doing it all locally so I'm not sure if I can even use it.
It looks to me like I'm allowing all I need, but I guess it's not enough.
If you're going to mark as a duplicate, please at least make sure my issues are covered by the answer.
There's a node package called cors which makes it very easy.
$npm install cors
const cors = require('cors')
app.use(cors())
You don't need any config to allow all.
See the Github repo for more info: https://github.com/expressjs/cors
One reason might be you're using the route as localhost:8000 rather than http://localhost:8000.
USE
http://localhost:8000
DON'T USE
localhost:8000
if you add this header
res.setHeader('Access-Control-Allow-Origin', '*');
you're using credential mode (means you're sending some authentication cookie from your app) and as for CORS specification you cannot use the wildcard * in this mode.
you should change your Access-Control-Allow-Origin header to match the specific host who generated the request
you can change this line:
res.header('Access-Control-Allow-Origin', '*');
to
res.header('Access-Control-Allow-Origin', 'the ip address');
but to be more generic, something like this should work:
res.setHeader('Access-Control-Allow-Origin', req.header('origin')
|| req.header('x-forwarded-host') || req.header('referer') || req.header('host'));
in addition you have even to allow OPTIONS requests from the browser otherwise you will get a preflight request error.
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
To anyone else that this may help, I was using axios with withCredentials: true.
On my Express backend, I was simply doing,
app.use(cors())
What fixed it was either removing withCredentials: true from the React frontend or changing my backend to,
app.use(cors({ credentials: true }))
you have to allow OPTIONS method as well
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
the browser send it with any post request to other domain to check how it will communicate with this remote server.

How to set header in request crossirigin.me? ERROR: Origin: header is required

I attempt to send a request for my app in meteor js and when i send it, the browser shows me the below message: Origin: header is required
This happend when i send this: http://crossorigin.me/https://scholar.google.cl/citations?user=n1qKMYwAAAAJ&hl=es
I'm using the CORS proxy http://crossorigin.me/
How to set this origin header and where?
Thanks to all
try this code
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,token');
//res.setHeader('*');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});

CORS - Access-Control-Allow-Origin issue

I have an AngularJS web application with a RESTful Jersey Api as Backend.
I'm making a call to this API
function Create(user) {
return $http.post('http://localhost:8080/NobelGrid/api/users/create/', user).then(handleSuccess, handleError('Error creating user'));
}
This is the code of the API (POST):
/**
* This API create an user
*
* #param data
* #return
*/
#Path("create")
#POST
#Produces("application/json")
public Response create(String data) {
UserDataConnector connector;
JSONObject response = new JSONObject(data);
User userToCreate = new User(response.getString("surname"), response.getString("name"),
response.getString("mail"), response.getString("username"), response.getString("password"), 0);
try {
connector = new UserDataConnector();
connector.createUser(userToCreate);
} catch (IOException e) {
e.printStackTrace();
}
return Response.status(Response.Status.OK) // 200
.entity(userToCreate)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT").build();
}
/**
* CORS compatible OPTIONS response
*
* #return
*/
#Path("/create")
#OPTIONS
public Response createOPT() {
System.out.println("Called OPTION for create API");
return Response.status(Response.Status.OK) // 200
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS").build();
}
I've added an OPTION API for create in order to make that API CORS-compatible. In fact the API works well cause the OPTIONS API is called before the POST one and the user is created in my Database. Anyway on front end side I get this error:
XMLHttpRequest cannot load http://localhost:8080/NobelGrid/api/users/create/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 500.
Can anyone please help me?
UPDATE:
stack suggests this question No Access-Control-Allow-Origin header is present on the requested resource as possible duplicate but that solution doesn't work for me cause addHeader(String) is not present in Response Jersey API.
UPDATE 2
I solved the issue using this solution:
http://www.coderanch.com/t/640189/Web-Services/java/Access-Control-Origin-header-present
But I have another error. I will do another question cause I think it's a different argument.
Thanks in advanced!
I solved the issue using this solution:
http://www.coderanch.com/t/640189/Web-Services/java/Access-Control-Origin-header-present
But I have another error.
I will do another question cause I think it's a different argument.
Use CORS NPM and add as a middleware.
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
------------------------- Add this lines in your app.js -------------------------
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

Setting Access-Control-Allow-Origin doesn't work with AJAX/Node.js

I keep facing the same error over and over again:
XMLHttpRequest cannot load http://localhost:3000/form. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access. The response had HTTP status code 404.
I've read countless posts similar to this one and they all pretty much have the same answer, namely to add the following setting: res.setHeader('Access-Control-Allow-Origin', '*').
That's what I've been doing but it still doesn't work.
I gave an angular.js app on localhost:8000 (when a btn is clicked logsth() is called) and my node works on localhost:3000. Here's what they look like:
app.controller('Contact', ['$scope', function($scope) {
$scope.logsth = function(){
var datas = {'may':'4','june':'17'};
$.ajax({
url: 'http://localhost:3000/form',
method: 'POST',
crossDomain: true,
data: datas
});
};
}]);
And my node:
var express = require('express');
var router = express.Router();
var app = express();
app.use(function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
res.setHeader('Access-Control-Allow-Credentials', true);
next();
});
app.post('/form', function(req, res){
console.log("e-mail sent");
res.send('yey');
});
module.exports = router;
Not too much code here but for now I'm only looking to get rid of the error.
EDIT: When I use app.use(...) and app.post(...) and go to localhost:3000/form I get 404 error. But when I use router.use(...) and router.post(...) at least the link works fine. Also, there is no 'allow-origin' error, but I do get: POST http://localhost:3000/form 404 (Not Found). However, when I go to http://localhost:3000/form it displays the response and console.log. Should I leave it as router instead of app?
Just leave this single line did the trick for me:
res.setHeader('Access-Control-Allow-Origin', '*');
Update:
You can try to install cors module from npm.
The issue is that you're returning a wildcard origin (*) and trying to pass credentials (res.setHeader('Access-Control-Allow-Credentials', true);). You cannot to both. If you must use Access-Control-Allow-Credentials, then you will need to be explicit about the allowed origins in your Access-Control-Allow-Origin header.
So, either remove this:
res.setHeader('Access-Control-Allow-Credentials', true);
Or change the origins to this:
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:3000');

Why do the CORS settings for my Express.js backend not work?

I am trying to set CORS for my Express.js backend. Since I have a local and a remote version of the front end I want to allow a couple of URLS access to the backend. I have tried to use "*" and var cors = require('cors') app.use(cors()) but I get
Cannot use wildcard in Access-Control-Allow-Origin when credentials
flag is true.
I have tried using the dynamic settings for cors(), but there were no examples how to use it with Express's routes. I am now trying to create my own white list check with the code below but now I am getting
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:5000' is therefore not allowed
access. The response had HTTP status code 500.
What am I doing wrong?
UPDATE: It looks like the if statement is blocking the headers from being added so I tried to remove it to see what is happening with res.header('Access-Control-Allow-Origin', req.get("origin")); It is now giving me
Credentials flag is 'true', but the 'Access-Control-Allow-Credentials'
header is ''. It must be 'true' to allow credentials.
var whiteList = {
"http://localhost:5000": true,
"https://example-url.herokuapp.com": true
};
var allowCrossDomain = function(req, res, next) {
if(whiteList[req.get('Origin')]){
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.get('Origin'));
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Origin, Accept');
next();
}
};
app.use(allowCrossDomain);
This ultimately came down to a spelling/understanding error. I was trying to get the request origin by using req.headers.Origin. Turns out there is no 'Origin' in headers, I had to use req.headers.origin instead. The code bellow will work, and let you use multiple urls for CORS, it does not yet easily handle something like http://localhost:5000/route or a situation where the provided origin isn't in the list.
var whiteList = {
"http://localhost:5000": true,
"https://example-url.herokuapp.com": true
};
var allowCrossDomain = function(req, res, next) {
if(whiteList[req.headers.origin]){
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Origin, Accept');
next();
}
};
app.use(allowCrossDomain);

Categories

Resources