I am having trouble with a node.js/express application I am trying to run.
When running on localhost, the data I pass to the route is parsed and I am able to use req.body.message successfully. However on my live site, this only returns undefined. Why is this, and how do I fix it?
This is the node.js app I am using on both the localhost and the live server.
const express = require("express");
const cors = require("cors");
const router = express.Router();
const app = express();
router.post("/send", (req, res) => {
res.send(`message is ${req.body.message}`);
});
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/", router);
const PORT = 3030;
app.listen(PORT, () => console.log("Server on " + PORT));
If I do a POST with "message":"hello", on my localhost, I get the response with the "message is hello", but on the live server I get "message is undefined".
Any advice appreciated, cheers.
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
Try putting all this middleware before '/send' API end point. Also check console errors that will give you more information about error.
I solved it. When calling the live api, you need to include a trailing slash.
E.g. examplewebsite.com/send will not work. However, examplewebsite.com/send/ will work.
I don't know enough about how servers work to explain this, but it solved my problem. I hope anyone else with this issue can benefit from my finding.
Related
I have problems receiving request in body format on my server.
I am using Express version 4.17.1. The documentation indicates that I don't have to use body-parserer, but I can do it directly with the express functionality "express.json ()"
However, I've been trying to get it to work for a long time but nothing happens: the console does not show anything. It seems that it does not recognize the request at all.
I'm doing all the request from Postman in body format JSON.
This is my code:
const express = require("express");
const formidable = require("express-formidable");
const cors = require("cors");
const dotenv = require("dotenv").config();
const app = express();
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(formidable());
app.use(cors());
(...)
app.post("/list", async (req, res) => {
try {
console.log(req.body);
} catch (error) {
return res.status(400).json({ message: error.message });
}
});
What am I doing wrong?
Thank you very much for your time and help in advance.
Express parse request body according to defined type in Content-Type header. Try to do request with header Content-Type: application/json.
I have a nodejs server running the common framework express. I have noticed recently that when I make requests from my server, I get this error at seemingly random times, for example, if I were to make a request twice, the error would usually only happen the first request, and not the second. I'm having trouble pinpointing what is causing this error, because I often write my code in one go, then test it later. Here is the error in full:
TypeError: Cannot read property 'app' of undefined
at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
at process._tickCallback (internal/process/next_tick.js:68:7) 'Unhandled Rejection at Promise' Promise {
<rejected> TypeError: Cannot read property 'app' of undefined
at json (/home/user/Desktop/project/node_modules/express/lib/response.js:256:18)
at process._tickCallback (internal/process/next_tick.js:68:7) }
All that I can tell from this error is that it may involve some reference to "app", however I am not sure what it could be specifically, as I haven't changed anything pertaining to "app" in express recently. Here is my express configuration on my server file:
const express = require('express'),
user = require('./routers/User.js'),
helmet = require('helmet'),
app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);
//map router files to respective urls
//these are stored in a directory and set above, these contain all of the handlers for each of my routes
app.use('/user', user);
//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));
If anything else is needed of me, please ask. I've tried to include every reference pertaining to the word "app" in my code, but that may not be enough.
EDIT: I thank you all for trying to help, but the code I provided was not intended to work, it was simply an example of what I import, this is an error with express, and I'm just trying to find out what kind of behavior would cause it. Sorry for the confusion.
You are most likely missing a comma after "helmet = require('helmet')
const express = require('express'),
user = require('./routers/User.js'),
helmet = require('helmet'),
app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);
//map router files to respective urls
//these are stored in a directory and set above, these contain all of the handlers for each of my routes
app.use('/user', user);
//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));
for your code to work you have to add
const express = require('express'),
user = require('./routers/User.js'),
helmet = require('helmet')
----> const app = express();
or helmet = require('helmet'), <-----
app = express()
//Worked fine for me. removed ur local import. This runs fine.
const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const bodyParser = require('body-parser')
app = express();
app.use(helmet());
app.use(cors());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.set('trust proxy', true);
//set port and listen on it
app.listen(5000, () => console.log("Server running on port 5000"));
I'm trying to create a basic login script for an app using Express JS, and have been working on a POST function to perform the same task for me. However, whenever I try to echo back the parameters I'm passing (testing the script via Postman), the values are always undefined.
Would appreciate some help! Thanks :)
Code:
const express = require('express'),
app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/',(request,response)=>{
response.send('This is a test message');
});
app.post('/login', (request,response)=>{
let uname = request.body.username;
let pword = request.body.password;
response.send('Username: ' + uname + ' and Password: ' + pword);
});
//Binding the server to a port(3001)
app.listen(3001, () => console.log('express server started at port 3001'));
JSON being passed:
{
"username":"testuname",
"password":"passw0rd"
}
What you have works fine.
You are probably not specifying the Content-Type of your request to be application/json when testing.
I think you should try as like as give below:
It works on my machine. As you might have seen that, I have select raw and JSON(application/json) which you might have been missing.
Here's my app.js file.
var express = require('express'),
bodyParser = require('body-parser'),
oauthServer = require('oauth2-server'),
oauth_model = require('./app_modules/oauth_model')
const app = express()
app.use(bodyParser.urlencoded({ extended: true }));
var jsonParser = bodyParser.json();
app.oauth = oauthServer({
model: oauth_model, // See below for specification
grants: ['password', 'refresh_token'],
debug: process.env.OAUTH_DEBUG,
accessTokenLifetime: 172800,
refreshTokenLifetime: 172800,
authCodeLifetime: 120,
});
// Oauth endpoint.
app.all('/oauth/token', app.oauth.grant());
// User registration endpoint.
app.post('/users', jsonParser, require('./routes/register.js'));
// Get user details.
app.get('/users', app.oauth.authorise(), require('./routes/users.js'));
app.post('/', app.oauth.authorise(), require('./routes/test.js'));
app.use(app.oauth.errorHandler());
app.listen(3000, function () {
console.log('Mixtra app listening on port 3000!')
})
When I send an invalid json body with POST request to localhost:3000/users the request goes to register.js and the validation code works there.
but strangely when I send valid JSON body, it says "Cannot POST /users" with a 404 Not Found HTTP status code and nothing in terminal log.
Note: I'm using postman to send the api requests.
It would be really great if someone could help me with this.
Thanks,
Joy
I don't see you using the jsonParser
You should use it before sending any json to it
app.use(jsonParser);
When using the following:
var app = require('express')();
var bodyParser = require('body-parser');
app.post('/test', bodyParser.json(), function(req, res) {
res.json(req.body);
});
var port = 4040;
app.listen(port, function() {
console.log('server up and running at port: %s', port);
});
and the following post from Postman:
I get an empty response. I've followed a lot of threads on using bodyParser.json() and for some reason I'm still receiving an empty object in response. What am I missing?
To make bodyParser.json works you should provide Content-Type header with value application/json in your requests.
A safer way to use body-parser would be to apply it as middleware for the entire app. The code will have to be refactored in this manner:
// Permit the app to parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// Use body-parser as middleware for the app.
app.use(bodyParser.json());
app.post('/test', function(req, res) {
res.json(req.body);
});
When you make a request on Postman, make sure to select the x-www-form-urlencoded tab as opposed to the raw tab.