Req.body empty whereas I tried all configuration - node.js

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);

Related

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();
});

Access origin issue on Express application

I have created an express application with angular ui. I have following the app.js file
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var userRouter = require('./routes/user');
var app = express();
// view engine setup
app.use(express.static(__dirname + '/dist'));
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(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/student', userRouter);
// catch 404 and forward to error handler
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(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I got error like this
request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin. is therefore not allowed access.
Try to set multiple fields at once, pass an object as the parameter. For example,
res.set({
"Access-Control-Allow-Origin", "*",
"Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"
});
Can you implement like this and check.
OR
If you want to work quick as of now, there is a hack code for chrome. Run this
In Windows, paste this command in run window
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security
Actually this problem must be solved from the server side (API). If you are in testing locally or you are in different domain then you must allow the CORS from the API Implementation.
You can use CORS extension of chrome for development purpose

Can't get nodeJS Express post to display body data

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.

How to use a middleware router for a sub path in express nodejs

I would like to sue a middleware just for the /doc path so it can serve satic file and have a basic auth.
But when i try to get /doc i have a cannot get /doc error.
Does anyone have any idea ?
var app = express();
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()) ; // parse application/json
app.use(functio //app.use('/doc', express.static('./doc'));n(req, res, next) {
res.header("X-powered-by", "NodeJs");
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization");
next();
});
app.use(function(req, res, next) {
console.log(' - ',req.originalUrl);
next();
});
var router = express.Router();
router.use(express.basicAuth('testUser', 'testPass'));
router.get('/doc', function(req, res, next) {
console.log("inside doc");
express.static('./doc');
next();
});
app.use('/conf',require('./v1/data_config'));
thanks and regard
2 Things:
You have to add your router to your express app and you should move the '/doc' route outside of your router as authentication could interfere with your app.
var router = express.Router();
router.use(express.basicAuth('testUser', 'testPass'));
router.get('/', express.static('doc'));
app.use('/doc',router);

Enable CORS in nodejs with ejs template

I repeatedly receive type errors and empty responses from what may be a CORS issue. I am new to nodejs and am having problems enabling CORS in my application. What is wrong with the following configuration for app.js, where I tried to apply
app.all('*',function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
immediately after var app = express();
Here is the full app.js file:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.all('*',function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
I consistently receive:
OPTIONS http://104.236.99.212:6790/ net::ERR_EMPTY_RESPONSE
undefined:1 Uncaught (in promise) TypeError: Failed to fetch(…)
Any help would be really appreciated! Thank you
In your ExpressJS app on node.js, do the following with your routes:
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.get('/', function(req, res, next) {
// Handle the get for this route
});
app.post('/', function(req, res, next) {
// Handle the post for this route
});

Resources