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)
Related
require('dotenv').config();
const express = require('express');
const app = express();
const cors = require('cors');
app.use(cors);
const connectDB = require('./config/mongoDB');
const PORT = process.env.PORT || 8000;
// body parser
app.use(express.json({ extended: false }));
//router
app.use(
'/',
require('./routes/index')
);
app.listen(PORT, (req, res) => {
connectDB();
console.log('listening on port ' + PORT);
});
so this is my express server code, it was working yesterday but I can't reach localhost: PORT (via postman and browser) today but it is running and listening to PORT. Where it goes wrong?
The cors middleware should be called with parenthesis, as a function:
app.use(cors());
You are setting the body parser middleware incorrectly, change
app.use(express.json({ extended: false }));
to:
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
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}`);
})
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've been banging my head against the wall on this one for a few hours. I'm not sure why it doesn't work but it's probably something simple I'm missing. It usually is...
Anyway, I'm doing a simple HTTP PUT from Angular 7 like this:
protected put(cmd: string, body: any) {
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
console.log(body);
return this._http.put(cmd, body, {headers: headers});
}
cmd and body are being passed in. I can see the body print out in the console and the cmd path is correct to hit my route path in Node.
From there, it comes into my Node/Express app. Which goes as follows:
'use strict';
const express = require('express');
const bodyParser = require('body-parser')
// Constants
const PORT = 8080;
const HOST = '0.0.0.0';
// App
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(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", "Origin, X-Requested-With, Content-
Type, Accept");
next();
});
app.use('/api', require('./routes/routes'));
app.use('/api/add-user', require('./routes/add-user/routes'));
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
And this is my routes file that console prints the empty body:
const express = require('express');
const router = express.Router();
const dvAdmin = require('../../controller/controller');
//Routes
//GETS
//PUTS
router.put('/addCCUser', function (req, res) {
console.log(req.body);
});
module.exports = router;
Unfortunately I get an empty body: {} in the request object, when I POST something to my api via Insomnia (configuration Form Form URL Encoded Header Content-Type: application/x-www-form-urlencoded):
Here is my express code:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/api/', function(req, res) {
test = req.body.test;
console.log(req);
console.log(test);
res.send("Hallo");
});
const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
What am I doing wrong? And also what would I have to change in my code if I'd configure Insomnia to Form as JSON, Header Content-Type: application/json ?
For accessing request body use body-parser middleware and for sending the response in JSON format use res.json()
https://www.npmjs.com/package/body-parser
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.post('/api/', function(req, res) {
test = req.body.test;
console.log(req);
console.log(test);
res.json({"message":"Hallo"}); //update here
});
const port = 4000;
app.listen(port, () => console.log(`Listening on port ${port}...`));
available in Express v4.16.0 onwards:
app.use(express.urlencoded({ extended: false }));
app.use(express.json());