I'm trying to communicate with the front react at localhost:3000 and the backend side nodeJS is localhost:5000 but the problem I keep getting this message and I can't find a solution how to solve it
Access to XMLHttpRequest at 'http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NSheHsx' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
GET-polling-xhr.js:268 GET http://localhost:5000/socket.io/?EIO=3&transport=polling&t=NShel1V net::ERR_FAILED
I tried every solution on the internet but without any chance
var corsOptions = {
origin: "https://localhost:3000/",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
this is the server.js
require("dotenv").config();
const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
const loadRoutes = require("./routes/index");
const app = express();
var server = require("http").createServer(app);
var io = require("socket.io")(server);
const path = require("path");
let stream = require("./controllers/stream");
var corsOptions = {
origin: "https://localhost:3000/",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
app.use(cors(corsOptions));
app.use(express.json());
app.use(fileUpload());
// database config
require("./config/db");
//require config
require("dotenv").config({
path: "./config/config.env",
});
//config for only developement
if (process.env.NODE_ENV === "developement") {
app.use(
cors({
origin: process.env.CLIENT_URL,
})
);
}
app.use(morgan("dev"));
//load all routes
loadRoutes(app);
io.of("/stream").on("connection", stream);
//---------------------------------------------
app.use((req, res, next) => {
res.status(404).json({
success: false,
message: "Page Not found",
});
});
//start our web server and socket.io server listening
server.listen(process.env.PORT, function () {
console.log(`listening on ${process.env.PORT}`);
})
changes that I made based on answer below but same error
require("dotenv").config();
const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
const loadRoutes = require("./routes/index");
const app = express();
var server = require("http").createServer(app);
var io = require("socket.io")(server);
const path = require("path");
let stream = require("./controllers/stream");
var corsOptions = {
origin: "http://localhost:3000/",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
// add this headers to your request and yow problems will be gone.
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cors(corsOptions));
app.use(express.json());
app.use(fileUpload());
// database config
require("./config/db");
//require config
require("dotenv").config({
path: "./config/config.env",
});
//config for only developement
if (process.env.NODE_ENV === "developement") {
app.use(
cors({
origin: process.env.CLIENT_URL,
})
);
}
app.use(morgan("dev"));
//load all routes
//cors anwser2
app.option("*",cors())
loadRoutes(app);
io.of("/stream").on("connection", stream);
//---------------------------------------------
app.use((req, res, next) => {
res.status(404).json({
success: false,
message: "Page Not found",
});
});
//start our web server and socket.io server listening
server.listen(process.env.PORT, function () {
console.log(`listening on ${process.env.PORT}`);
})
Any idea on solving this error ?
have you already tried enabling PREFLIGH like described on 'cors' lib?
There is a section on the docs explaining about 'complex' requests that need to make a preflight request before making the actual request.
Here is a simple way to enable to test:
app.options('*', cors()) // include before declaring the route
I got this information from this section on the readme here: https://www.npmjs.com/package/cors#enabling-cors-pre-flight
Tho it's not recomended using wildcard '*' in production, so be careful :)
hope I helped
yow broh, you need to add them access-control headers
at yow code before your routes add it to express.
also I see you have
var corsOptions = {
origin: "https://localhost:3000/",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
your origin cannot be "https://localhost:3000/" in localhost change it to "http://localhost:3000/"
require("dotenv").config();
const express = require("express");
const morgan = require("morgan");
const cors = require("cors");
const loadRoutes = require("./routes/index");
const app = express();
var server = require("http").createServer(app);
var io = require("socket.io")(server);
const path = require("path");
let stream = require("./controllers/stream");
var corsOptions = {
origin: "https://localhost:3000/",
optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
};
// add this headers to your request and yow problems will be gone.
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cors(corsOptions));
app.use(express.json());
app.use(fileUpload());
// database config
require("./config/db");
//require config
require("dotenv").config({
path: "./config/config.env",
});
//config for only developement
if (process.env.NODE_ENV === "developement") {
app.use(
cors({
origin: process.env.CLIENT_URL,
})
);
}
app.use(morgan("dev"));
//load all routes
loadRoutes(app);
io.of("/stream").on("connection", stream);
//---------------------------------------------
app.use((req, res, next) => {
res.status(404).json({
success: false,
message: "Page Not found",
});
});
//start our web server and socket.io server listening
server.listen(process.env.PORT, function () {
console.log(`listening on ${process.env.PORT}`);
})
Related
I'am hosting my Angular frontend and Node backend in Firebase Hosting and Firebase Functions respectively. But I keep getting CORS error on POST methods. I have tried almost every solution available in Stackoverflow and other websites. I' am including my error response and code below.
Access to XMLHttpRequest at
'https://us-central1-#########.cloudfunctions.net/apps/auth/api/feed/update'
from origin 'https://#########.web.app' has been blocked by CORS
policy: No 'Access-Control-Allow-Origin' header is present on the
requested resource.
const functions = require("firebase-functions");
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const userRoutes = require("./route/user");
const feedRoutes = require("./route/feed");
const cors = require('cors');
const app = express();
// ESTABLISHING DATABASE CONNECTIONS
mongoose
.connect(
"mongodb+srv://#####-###-####-####:"
+ functions.config().env.mongo_atlas_pw +
"####-####-####.antdw.mongodb.net/"
+ functions.config().env.mongo_atlas_db +
"?retryWrites=true&w=majority"
, { useNewUrlParser: true , useUnifiedTopology: true })
.then(() => {
console.log("Connected to database!");
})
.catch(() => {
console.log("Connection failed!");
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use("/images", express.static(path.join(__dirname, "images")));
app.use("/", express.static(path.join(__dirname, "angular")));
// IF BACKEND AND FRONTEND ARE HOSTED SEPERATELY
// app.use((req, res, next) => {
// res.setHeader('Access-Control-Allow-Origin', '*');
// res.setHeader(
// "Access-Control-Allow-Headers",
// "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Headers, Accept, Authorization"
// );
// res.setHeader(
// "Access-Control-Allow-Methods",
// "GET, POST, PATCH, PUT, DELETE, OPTIONS"
// );
// next();
// });
var corsOptions = {
origin: '*',
allowedHeaders: ['Content-Type', 'Authorization', 'Content-Length', 'X-Requested-With', 'Accept', 'Origin', 'Access-Control-Allow-Headers'],
methods: ['GET', 'POST', 'DELETE', 'OPTIONS']
}
app.options('*',cors());
app.use(cors(corsOptions));
app.use("/auth/api/user", userRoutes);
app.use("/auth/api/feed", feedRoutes);
app.use((req, res, next) => {
res.sendFile(path.join(__dirname, "angular", "index.html"));
});
exports.apps = functions.https.onRequest(app);
Looks like my CORS error was not actually a CORS error. My code was fixed after i changed the parameter limit of body parser package on server. also i needed some rewriting on my form data submission at angular frontend.
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));
I've been working on chat functionality. There are two kinds of clients, One is the frontend of my application and the second is random another website.
I know there are plenty of issues like this but I tried all of the solution but I'm still getting following error:
Access to XMLHttpRequest at 'https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjoM1w' from origin 'null' 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.
and this the error I'm getting on client-side of my own front end:
https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjnJUX 404 (Not Found)
This is how I'm trying to connect from client-side.
var socket = io.connect("https://mydomain:443/", {secure: true, port: '443'});
and this is my server.js code
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const base = require("./routes/api/base");
const leads = require("./routes/api/leads");
const requests = require("./routes/api/requests");
const offApp = require("./routes/api/offApp");
const chat = require("./routes/api/chat");
const chatSocket = require("./routes/socket/chat");
const path = require("path"); // on top
const app = express();
// const client = require('socket.io').listen(4000).sockets;
const https = require('https');
const fs = require('fs');
var options = {
pfx: fs.readFileSync('certificate.pfx'),
passphrase: 'password'
};
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-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, *');
next();
});
var server = https.createServer(options, app);
var client = require("socket.io").listen(server);
client.origins('*:*') ;
server.listen(443);
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }, (err, db) => {
if (err) {
throw err;
}
console.log('MongoDB connected');
chatSocket(db, client);
});
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/base", base);
app.use("/api/leads", leads);
app.use("/api/requests", requests);
app.use("/api/offapp", offApp);
app.use("/api/chat", chat);
const port = process.env.PORT || 5000;
app.use(express.static("client/build")); // change this if your dir structure is different
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
Please help me resolve this CORS and other issues. I am using the Azure app service. That's why I can't use any other port than 80 and 433
Install cors package using npm i cors
In your app.js file,
const cors = require('cors')
app.use(cors());
// use CORS like that-
// you need to use it as middle ware
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Danish try this solution, I hope it will work
const client = 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();
}
});
client.on("connection", () => {
console.log("Connected!");
});
server.listen(443);
I have this error I don't know why in my back end node js I'm using cors
const express = require('express');
const bodyParser = require('body-parser');
const port = 8080;
const cors = require('cors');
require('./database/index')
const usersRouter = require('./routes/userRoutes');
const postRouter = require('./routes/post');
const app = express();
const router = express.Router();
usersRouter.configuration(router);
postRouter.configuration(router);
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port',port);
app.use('/', router);
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
my method front - end:
signIn = () => {
const data = {login:this.login,password:this.password};
const requestInfo = {
method:'POST',
body: JSON.stringify({data}),
headers: new Headers({
'Content-Type': 'application/json'
}),
};
fetch('http://localhost:8080/login', requestInfo)
.then(response => {
if(response.ok){
return response.json();
}
throw new Error("Login Invalido..")
})
.then(token => {
sessionStorage.setItem('token', JSON.stringify(token.token));
this.props.history.push("/users");
return;
})
.catch(e => {
this.setState({message: e.message})
});
}
error:
Access to fetch at 'http://localhost:8080/login' from origin
'http://localhost:3000' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: 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.
Try to put CORS before router configuration.
const express = require('express');
const bodyParser = require('body-parser');
const port = 8080;
const cors = require('cors');
require('./database/index')
const usersRouter = require('./routes/userRoutes');
const postRouter = require('./routes/post');
const app = express();
const router = express.Router();
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('port',port);
usersRouter.configuration(router);
postRouter.configuration(router);
app.use('/', router);
I am creating a REST api using Node.js And Express, The application works fine including routes and other functanalities on local computer but when uploaded to windows server routes are not working properly, I was able to see Hello World printed on my from home page e.g:- www.abcd.com/,
But when routes are being used eg:- www.abcd.com/users/ it gives 404 - File or directory not found.
Here is my code
server.js
const http = require('http')
const app = require('./app')
const server = http.createServer(app);
server.listen(process.env.PORT, () => {
console.log("Server Started");
});
app.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const app = express();
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header(
'Access-Control-Allow-Origin',
'*'
);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-with, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
const users_routes = require('./api/routes/users.routes');
const message_routes = require('./api/routes/message.routes');
const group_routes = require('./api/routes/group.routes');
const key_routes = require('./api/routes/key.routes');
console.log(users_routes.toString());
app.use('users', users_routes);
app.use('message', message_routes);
app.use('group', group_routes);
app.use('key', key_routes);
app.use('/', (req, res, next) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<H1>Hello World!</H1>');
});
module.exports = app;
user.routes.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
Console.log("Hello there");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<H1>Hello World!</H1>');
});
module.exports = router;
Log file after starting app
Server Started
It prints function when used typeof(user_routes)
I use Axios to sending request to my NodeJS server. This is my request:
let url = 'http://example.com:1337/api/'
let config = {
headers: {
'Content-Type': 'application/json'
}
}
settings = (data) => {
return axios.post(url + 'settings', JSON.stringify(data), config)
.then( res => res.data)
.catch(e => console.log(e))
}
In NodeJS/ExpressJS server:
const express = require('express')
const App = express()
let bodyParser = require('body-parser')
// ... Mongoose and etc.
var cors = require('cors')
App.use(cors())
App.options('*', cors());
App.use("/data", express.static(__dirname + '/data'));
App.use(bodyParser.urlencoded({
extended: true
}));
App.use(bodyParser.json())
App.use('/api', require('./routes/Users'))
App.listen(1337)
But request to http://example.com:1337/api/settings returns (firefox):
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com:1337/api/settings. (Reason: CORS request did not succeed)
Thank you for your solutions.
// server.js
const express = require('express');
const app = express();
const routes = require('./routes');
const PORT = process.env.PORT || 5000;
// configure body parser for AJAX requests
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(routes);
//Server
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}.`);
});
Try this:
const express = require('express')
const App = express()
let bodyParser = require('body-parser')
// ... Mongoose and etc.
App.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST","PUT");
next();
});
App.use("/data", express.static(__dirname + '/data'));
App.use(bodyParser.urlencoded({
extended: true
}));
App.use(bodyParser.json())
App.use('/api', require('./routes/Users'))
App.listen(1337)