I have a site written in Laravel and Vue.js, nodejs is also used. When I try to enter the site using the http protocol, everything is fine, when I try to enter the https protocol, half of the site does not load and in the console I get an error:
Access to XMLHttpRequest at 'https://example.com:8443/socket.io/?EIO=3&transport=polling&t=NPIJFIo' from origin 'https://example.com' has been blocked by CORS policy: No 'Access- Control-Allow-Origin 'header is present on the requested resource.
Redirection to https is configured on nginx itself, but I cannot do it on nodejs. Also i can't understand, how to correct add ssl cert path to my app.js.
My app.js:
const app = require('express')(),
server = require('https').createServer(app),
Redis = require('redis'),
RedisClient = Redis.createClient(),
io = require('socket.io')(server),
cors = require('cors'),
axios = require('axios');
const myArgs = process.argv.slice(2);
const domain = myArgs[0];
const SECRET_KEY = 'cZN^ZH8)mu~9e,>6M>3qKV=Ar^fFF,7/';
axios.defaults.baseURL = 'https://example.com/api/bot/';
server.listen(8081);
app.use(cors({
origin: true,
credentials: true
}));
What am I doing wrong? I would be grateful for help.
It's the CORS issue, and you need to add cors option for the socket.io server.
Refer to Handling CORS for Socket.io.
io = require('socket.io')(server, {
cors: {
origin: '*'
}
});
Related
I am using the code below to run my nodejs backend server. Angular front end has to communicate with the server. While I am using it on localhost everything works fine. However when I deploy my code on heroku I keep getting
Access to XMLHttpRequest at 'heroku app link' from origin 'https:https://iprocopiou.com/.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Does anyone know what I am missing here?
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const corsOptions = {
origin: "*",
methods: ["GET","HEAD","PUT","PATCH","POST","DELETE"],
credentials: true,
preflightContinue:false
}
require("./startup/logging")();
require("./startup/routes")(app);
require("./startup/db")();
require("./startup/config")();
require("./startup/validation")();
require("./startup/prod")(app);
app.use(cors(corsOptions))
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
const port = process.env.PORT || 3000;
app.listen(port, () =\> console.log(`Listening on port ${port}`));
I have tried almost every solution that I found...
For security reasons you need to specify the exact URL or URLS origin (protocol + domain + port) when you want to allow and share credentials, you cannot use *.
const corsOptions = {
origin: "https://iprocopiou.com", // or your exact URL you allow to make request
methods: ["GET","HEAD","PUT","PATCH","POST","DELETE"],
credentials: true,
preflightContinue:false
}
//...
app.use(cors(corsOptions))
you can also see more detail in this threat CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
I have a REST API running on Node JS with Express.
I keep having issues with CORS because the front end is HTTPS and the backend API is HTTPS which frequently, but not always gets reported as a violation.
I am trying to secure the API with a Let's Encrypt cert but I seem to be missing something.
Here is the code that initializes the express server:
require('dotenv').config();
const https = require("https"),
fs = require("fs");
const app = require("./src/app");
const port = process.env.PORT || 8000;
https
.createServer(
{
key: fs.readFileSync('/etc/letsencrypt/live/myserver.com/privkey.pem', 'utf8'),
cert: fs.readFileSync('/etc/letsencrypt/live/myserver.com/fullchain.pem', 'utf8')
},
app
)
.listen(8000, function() {
console.log('HTTPS listening on PORT 8000');
});
Is there another approach? Or am I just doing it wrong?
CURL still works on HTTP which surprises me. There shouldn't be an HTTP server listening on 8000. GET calls work without the SSL configuration but POSTs always fail.
All the APIs work locally, it's just when I push it to production that it fails. But then, locally, it's not running HTTPS so there is no violation.
I haven't seen posts that address this specifically so I have to wonder what I'm missing. This has to be a common scenario.
Thanks for any help.
Try either of these solutions, whatever suits you:
import * as Cors from 'cors';
const cors = Cors( { origin: true } );
app.use( cors );
var cors = require('cors');
var app = express();
app.use(cors());
I'm having issues with CORS in production when using React, Socket.io, and Node.js.
Client Side:
import { io } from 'socket.io-client';
const socket = io('https://warm-wildwood-81069.herokuapp.com');
Server Side:
const app = require("express")();
const server = require("http").createServer(app);
const io = require("socket.io")(server, {
cors: {
origin: "https://priceless-swirles-68e598.netlify.app",
methods: [ "GET", "POST" ]
}
});
Both client and server are running 4.0.0 version of Socket.io.
The errors that I'm getting are as follows:
Access to XMLHttpRequest at 'https://warm-wildwood-81069.herokuapp.com/socket.io/?EIO=4&transport=polling&t=NXV7rQn' from origin 'https://priceless-swirles-68e598.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
and:
GET https://warm-wildwood-81069.herokuapp.com/socket.io/?EIO=4&transport=polling&t=NXV7rQn net::ERR_FAILED
Live Demo: https://priceless-swirles-68e598.netlify.app
I have a chat application where my client side is written in Reactjs and my backend is written in Nodejs/Express. I have required cors and everything on my backend and the entire application worked perfectly when I was using localhost:3000 for the client and localhost:5000 for the server. I then deployed the server to heroku and the client to netlify, and now I am getting this CORS error every time I try to log in using a POST request (using axios as well):
Under the network tab on chrome, I get two things, a "signin" that has 204 and it works, and then a "signin" that just says error.
This is what my backend looks like in Nodejs/express:
require('dotenv').config()
const http = require('http');
const cors = require('cors');
const hostname = '127.0.0.1';
const port = process.env.PORT || 5000;
const express = require('express');
const jwt = require('jsonwebtoken')
const cookieParser = require('cookie-parser');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const {AddUser, FindUser, RemoveUser, FindId} = require('./users.js')
var corsOptions = {
origin: ['http://localhost:3000', 'https://easytalkchat.netlify.app'],
credentials: true,
methods: ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'] };
app.use(cors(corsOptions));
app.use(express.json())
app.use(cookieParser());
//Tells the server what port to listen to and can add a function to talk to command line
server.listen(port, () => {
console.log("Server is up!");
});
What I THINK might be the problem is maybe I'm not setting up the server using https, because I'm doing it with http. Maybe this is causing the problem but I don't know how to fix it. Other people have also mentioned it might not be a problem with CORS but rather Heroku, since Heroku only installs devDependencies or something like that, but I don't know how to fix that either.
I've tried adding headers, credentials, everything, I have no clue.
My front end looks like this:
const signIn = (e) => {
e.preventDefault();
axios.post('https://easytalkchatapp.herokuapp.com/signin', {
username: username,
password: password
}).then(res => {
...
and I have axios.defaults.withCredentials = true written at the top.
And just to re-state above, if I literally go to terminal and just run my server on localhost:5000 instead of heroku and make all my POST/GET requests through the localhost:500 server it works completely fine. If, however, I run my client on localhost:3000 and have the server be heroku, it breaks, so the problem is most certaintly with heroku and how I'm using it.
Since, you are using withCredentials, so I thinks its better to provide specific values for origin instead of true or '*' because it will not work with credentials true.
Try using this options:
var corsOptions = {
origin: ['http://localhost:3000', 'https://easytalkchat.netlify.app'],
credentials: true,
};
I hope it helps.
if you use withCredentials= true and when you run frontend and backend both form localhost, it runs perfectly because they are in the same origin
but if you run frontend and backend from different origin(host) in that time it gives you cors issue. for resolve this issue you have to whitelist the frontend origin in the backend
var corsOptions = {
origin: ['http://localhost:3000', 'https://easytalkchat.netlify.app'],
credentials: true,
};
by this way backend now trust the frontend origin
It turns out it was completely my own fault with my backend code. I was using process.env.(variable) and I had never specified it in the heroku config vars so it kept breaking when trying to access it. UGH. Thanks everyone.
We are using CORS to allow all origins
app.use(cors());
server running on port 4000, and client running on 3000
here is my server.js code
const cors = require("cors");
const http = require("http");
const socketIO = require("socket.io");
app.use(cors());
const port = process.env.PORT || process.env.DEFAULT_PORT;
console.log("port: ", port);
app.listen(port, () => {
console.log(`App listening at ${port}...`);
});
const server = http.createServer(app);
const io = new socketIO(server, {
transports: ["websocket"],
});
React js code
constructor(props) {
super(props);
try {
this.socket = io("http://localhost:4000", { transport: ["websocket"] });
this.socket.on("Chat-event", data => {
console.log("socketdata", data);
});
} catch (error) {
console.log("hiterror", error)
}
}
I am continuously getting this error on the client side after allowing origin for all.
Access to XMLHttpRequest at 'http://localhost:4000/socket.io/?EIO=3&transport=polling&t=Mv-SSIc' from origin 'http://localhost:3000' has been blocked by CORS policy: 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'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute
For socket.io version 3.x.x cors configuration has changed, I managed to fix it by adding options to the socket creation.
Tried on the version 2.x.x also and it worked.
const io = socketio(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}
});
Here is the resource https://socket.io/docs/v3/handling-cors/
Bonus: In case you encounter Bad Request make sure you have the same version of socket.io for the client and the server.
By following these steps you can get rid of these error.
// 1) on server side
const cors = require('cors');
const socketio = require('socket.io')
const http = require('http');
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: localhost:3000/, //your website origin
methods: ["GET", "POST"],
credentials: true
}
});
// 2) add these middlewares
app.use(cors())
app.options('*', cors());
// 3) on client-side
import io from 'socket.io-client'
let socket = io.connect(localhost:8080, { transports: ['websocket'] }) // your local server
try using the cors credentials config:
app.use(cors({credentials: true}));
Please allow all to socket.io at server side
const socketIO = require('socket.io')(server, { origins: '*:*'});
Or you can set socketIO origins as *
socketIO.set('origins', '*:*');
#user4860402 Gave me solution, thing is that by default npm is installing socket.io client v 2.X.X but on server I'm using latest verion (also provided by npm) 3.0.5
So all problems including 400 error comes because client and server verion doesnot match.
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const socketio = require("socket.io");
const cors = require("cors");
const io = socketio(http, {cors:{origin:"*"}});