Can't get nodeJS Express post to display body data - node.js

I feel like I've tried everything, would appreciate some fresh eyes to look upon my problem. As the title suggests, I'm sending a http post request to my NodeJS server that is running express, and nodeJS returns the req.body to be undefined/empty.
NodeJS Express Code:
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
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.post('/addComment', (req, res) => {
console.log(req.body);
});
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
Javascript Browser Code:
let data = {name: 'aName'};
fetch('http://localhost:5000/addComment', {
method: 'post',
body: JSON.stringify(data)
});

You have to use body-parser middleware :
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
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.post('/addComment', (req, res) => {
console.log(req.body);
});
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
see body-parser.

If you are using the latest express, you can actually use do
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;
app.use(express.json())
app.use (express.urlencoded({extended: false}))
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.post('/addComment', (req, res) => {
console.log(req.body);
});
app.listen(PORT, () => console.log(`Listening on ${ PORT }`));
Express now bundle body-parser by default due to popular demand.

Related

Access to XMLHttpRequest at 'xxx' from origin 'xxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the request

I've tried all possible settings but still can't fix this. I created my server with express nodejs and deployed it on Heroku. Everything works perfectly on my localHost (server and client), but not when the server is on Heroku.
I was reviewing all the answers on this question on stackoverflow and I still can't solve it ='(
const cors = require('cors');
const app = express();
mongoose.connect( process.env.MONGO_URL)
.then(() => {
console.log('Connected to database!');
})
.catch(() => {
console.log('DB Connection failed!');
});
app.use(cors({origin: true, credentials: true}));
app.use(express.json());
app.use(AUTH, authRoute);
app.use(USERS, userRoute);
app.use(PRODUCTS, productRoute);
app.use(CARTS, cartRoute);
app.use(ORDERS, orderRoute);
app.use(CHECKOUT, stripeRoute);
app.get('/', (req, res) => {
res.send('Hello to Greensai Updated!');
});
app.listen(process.env.PORT || 5000, () => {
console.log('Server started on port 5000');
});
Try using this code right in between app.use(express.json()); and app.use(AUTH, authRoute);
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();
});
This should allow your server to send a response back to the client.

CORS issue with React.js + Node.js(express)

I'm connecting my react-app with mysql now.
I tried proxy(in package.json), app.use(cors()) also Google chrome Cors Extension for catch this cors issue, but i couldn't. I need your help.
ERROR MSG
Access to XMLHttpRequest at 'localhost:4000/api/test'
from origin 'http://localhost:3000' has been blocked
by CORS policy: Cross origin requests are only supported
for protocol schemes: http, data, chrome, chrome-extension,
chrome-untrusted, https.
xhr.js:177 GET localhost:4000/api/test net::ERR_FAILED
I added this line in package.json
"proxy": "http://localhost:4000/",
server.js
const express = require("express");
const cors = require("cors");
const app = express();
const PORT = process.env.PORT || 4000;
const db = require("./config/db");
app.use(cors());
app.get("/", cors(), (req, res) => {
res.send("hello route / ");
});
app.get("/api/test", cors(), (req, res) => {
res.header("Access-Control-Allow-Origin", "*");
db.query("SELECT * FROM travel_test", (err, data) => {
if (!err) res.send({ data });
else res.send(err);
});
});
app.listen(PORT, () => {
console.log(`Server On : http://localhost:${PORT}/`);
});
api.js
import axios from "axios";
const api = axios.create({
baseURL: "localhost:4000/api/",
});
export const cityApi = {
test: () => api.get("test"),
};
Try this
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
OR
app.use(express.methodOverride());
// ## CORS middleware
//
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', 'Content-Type, Authorization');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.use(allowCrossDomain);
Add this code to your server.js file:
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, 'Content-Type' : 'multipart/form-data' ,* "
);
res.header(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT, DELETE, OPTIONS"
);
next();
});
before the app.use(cors());

How to solve No 'Access-Control-Allow-Origin' in express js?

I know that this question has been answered and some of them worked but for me it is not. I'm struggling to find a solution for this problem:
Access to XMLHttpRequest at 'http://lolcahost:9000/api/users' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I already tried downloading a chrome extension but didn't help me and using app.use(cors()) also didn't help me.
This is my code in expressjs
/* Importing all necessary packages. */
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
/* Default port */
const port = process.env.PORT || 9000;
/* Creating express object */
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/api', require('./routes/route'));
app.use(cors());
app.get('/', (request, response) => {
response.json({
HOME: "HELLO JSON"
})
});
app.listen(port, () => {
console.log(`Listening at port ${port}`)
});
and this is my code in vuejs where I'm trying to render the data.
getUsers() {
axios
.get("http://localhost:9000/api/users/")
.then(response => (this.results = response.data))
.catch(error => console.log(error));
}
You are using the cors middlware AFTER the /api routes. So, actually the cors middlware is not even being called. Put the cors above other middlwares.
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/api', require('./routes/route'));
Middlwares are called by the order they are initialised. Now, the /api is initialised first and is not a middleware(doesn't call the next() function) so after the routes any middleware is basically unreachable code.
Try this.
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8080"); // 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();
});
or
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();
});

Req.body empty whereas I tried all configuration

I send a post request to my test url bu req.body is empty.
I'm using NodeJS, Express & the middleware BodyParser.
Here my code :
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
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.post('/test/json/', function(req, res, next) {
res.json(req.body);
})
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.listen(8282);
In my req.body, it should disply {username:"Yacine"}
Please help me figure out with this cause I read all post looks like my problem & all solution provided are already used in my code.
Thanks
You must declare middlewares before routes so you can use them, try to change like this:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
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(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.post('/test/json/', function (req, res, next) {
res.json(req.body);
});
app.listen(8282);

node.js express routes are not working in remote server

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)

Resources