The Problem occurs while sending GET or any request with parameters in the URL.
for example my
index.js
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/:name", function (req, res) {
let name = req.params.name;
console.log("Hello " + name + " from /:name");
res.send("Hello " + name + " from /:name");
});
app.get("/", function (req, res) {
console.log("Hello world from /");
res.send("Hello world from /");
});
app.listen(3000, () => {
console.log("Server is running on port " + 3000)
});
For http://localhost:3000/ it's working perfectly fine.
the Problem is occurring when we try to hit /:name route
when we use URL http://localhost:3000/?name=NODE it is going to the same route as above. in /
But the crazy part is when we put http://localhost:3000/NODE which is simply a new different route that is not implemented.
It is getting the response from :/name which doesn't make any sense.
is it a BUG or I am doing something wrong or is it something new I am not aware of?
I am currently using Windows11,
this problem also occurs in my friend's PC who uses Ubuntu
When you define route as
/:name
That's called path parameter and it's used like this :
GET /yourname
And that's why this works :
GET /NODE
What you"re using to call the endpoint (?name=xxx) is called query parameter, you can get that name from '/' endpoint like this :
let name = req.query.name;
I think you're almost there, but /:name does not match /?name=, but it does match /NODE.
This is exactly what's expected to happen. If this surprised you, go re-read the documentation because it should be pretty clear on this.
I think I am confused between query parameters and params.
Let:
given this URL http://www.localhost:3000/NODE?a=Debasish&b=Biswas
We will have:
req.query
{
a: 'Debasish',
b: 'Biswas'
}
req.params
{
param1: 'NODE'
}
Here I am sending a query but want to receive params. That is where I go wrong.
For better understanding check :
Node.js: Difference between req.query[] and req.params
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.
I'm trying to send data using vue.js to my node.js server, but the browser console keeps showing me a 404: POST http://127.0.0.1:63342/myaction 404 (Not Found)
vue.js:
this.$http.post('http://127.0.0.1:63342/myaction', this.formData).then(response => {
console.log(response.body);
}
node.js:
var express = require('express');
var bodyParser = require('body-parser');
var exp = express();
exp.use(bodyParser.urlencoded({extended: true}));
exp.post('/myaction', function (req, res) {
res.send('saved: "' + req.body.name + '".');
});
exp.listen(63342, function () {
console.log('Server running at', this.address());
});
When I start my server, it says it's running at { address: '::', family: 'IPv6', port: 63342 }
The POST worked without vue.js, by simply submitting a HTML form, but now AJAX doesn't wordk. I tried multiple ports and folders, but can't figure out the mistake.
I finally figured it out. You have to manually add an address to the listener:
app.listen(63342, '127.0.0.1', function () {}
And in my case I was using the same port for API and Frontend, I had to switch ports and allow CORS
I am making a simple POST request using Alamofire (in iOS) and handling it in node using express.
My code in iOS:
let boop: [String: AnyObject] = ["username":"fakeuser"];
Alamofire.request(.POST,"http://localhost:3000/test", parameters: boop, encoding: .JSON)
And this is my code in node:
var app = require('express')();
var http = require('http').Server(app);
app.post('/test', function(req, res){
console.log("THE SERVER HAS RECEIVED THE POST! \n")
console.log(req.body);
});
http.listen(PORT, function(){
console.log('listening on *:3000');
});
My terminal console prints out "the server has received the post" , so I know that the post is actually triggered. The issue is that instead of logging the req.body, it instead prints out "undefined". I've looked around and it seems like a "body parser" thing needs to be configured but apparently that is obsolete with the new version of express. So I am lost as to what to do.
Any advice?
I'm pretty sure you need to add the body-parser to your express app to parse the JSON.
const bodyParser = require('body-parser');
app.use(bodyParser.json());
See http://expressjs.com/de/api.html#req.body.
I have the following Node.js code:
var express = require('express');
var app = express.createServer(express.logger());
app.use(express.bodyParser());
app.post('/', function(request, response) {
response.write(request.body.user);
response.end();
});
Now if I POST something like:
curl -d user=Someone -H Accept:application/json --url http://localhost:5000
I get Someone as expected. Now, what if I want to get the full request body? I tried doing response.write(request.body) but Node.js throws an exception saying "first argument must be a string or Buffer" then goes to an "infinite loop" with an exception that says "Can't set headers after they are sent."; this also true even if I did var reqBody = request.body; and then writing response.write(reqBody).
What's the issue here?
Also, can I just get the raw request without using express.bodyParser()?
Starting from express v4.16 there is no need to require any additional modules, just use the built-in JSON middleware:
app.use(express.json())
Like this:
const express = require('express')
app.use(express.json()) // <==== parse request body as JSON
app.listen(8080)
app.post('/test', (req, res) => {
res.json({requestBody: req.body}) // <==== req.body will be a parsed JSON object
})
Note - body-parser, on which this depends, is already included with express.
Also don't forget to send the header Content-Type: application/json
Express 4.0 and above:
$ npm install --save body-parser
And then in your node app:
const bodyParser = require('body-parser');
app.use(bodyParser);
Express 3.0 and below:
Try passing this in your cURL call:
--header "Content-Type: application/json"
and making sure your data is in JSON format:
{"user":"someone"}
Also, you can use console.dir in your node.js code to see the data inside the object as in the following example:
var express = require('express');
var app = express.createServer();
app.use(express.bodyParser());
app.post('/', function(req, res){
console.dir(req.body);
res.send("test");
});
app.listen(3000);
This other question might also help: How to receive JSON in express node.js POST request?
If you don't want to use the bodyParser check out this other question: https://stackoverflow.com/a/9920700/446681
As of Express 4, the following code appears to do the trick.
Note that you'll need to install body-parser using npm.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
For 2019, you don't need to install body-parser.
You can use:
var express = require('express');
var app = express();
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.listen(8888);
app.post('/update', function(req, res) {
console.log(req.body); // the posted data
});
You should not use body-parser it is deprecated. Try this instead
const express = require('express')
const app = express()
app.use(express.json()) //Notice express.json middleware
The app.use() function is used to mount the specified middleware function(s) at the path which is being specified. It is mostly used to set up middleware for your application.
Now to access the body just do the following
app.post('/', (req, res) => {
console.log(req.body)
})
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())
var port = 9000;
app.post('/post/data', function(req, res) {
console.log('receiving data...');
console.log('body is ',req.body);
res.send(req.body);
});
// start the server
app.listen(port);
console.log('Server started! At http://localhost:' + port);
This will help you. I assume you are sending body in json.
This can be achieved without body-parser dependency as well, listen to request:data and request:end and return the response on end of request, refer below code sample. ref:https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/#request-body
var express = require('express');
var app = express.createServer(express.logger());
app.post('/', function(request, response) {
// push the data to body
var body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
// on end of data, perform necessary action
body = Buffer.concat(body).toString();
response.write(request.body.user);
response.end();
});
});
In my case, I was missing to set the header:
"Content-Type: application/json"
Try this:
response.write(JSON.stringify(request.body));
That will take the object which bodyParser has created for you and turn it back into a string and write it to the response. If you want the exact request body (with the same whitespace, etc), you will need data and end listeners attached to the request before and build up the string chunk by chunk as you can see in the json parsing source code from connect.
The accepted answer only works for a body that is compatible with the JSON format. In general, the body can be accessed using
app.use(
Express.raw({
inflate: true,
limit: '50mb',
type: () => true, // this matches all content types
})
);
like posted here. The req.body has a Buffer type and can be converted into the desired format.
For example into a string via:
let body = req.body.toString()
Or into JSON via:
let body = req.body.toJSON();
If you're lazy enough to read chunks of post data.
you could simply paste below lines
to read json.
Below is for TypeScript similar can be done for JS as well.
app.ts
import bodyParser from "body-parser";
// support application/json type post data
this.app.use(bodyParser.json());
// support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
In one of your any controller which receives POST call use as shown below
userController.ts
public async POSTUser(_req: Request, _res: Response) {
try {
const onRecord = <UserModel>_req.body;
/* Your business logic */
_res.status(201).send("User Created");
}
else{
_res.status(500).send("Server error");
}
};
_req.body should be parsing you json data into your TS Model.
I'm absolutely new to JS and ES, but what seems to work for me is just this:
JSON.stringify(req.body)
Let me know if there's anything wrong with it!
Install Body Parser by below command
$ npm install --save body-parser
Configure Body Parser
const bodyParser = require('body-parser');
app.use(bodyParser);
app.use(bodyParser.json()); //Make sure u have added this line
app.use(bodyParser.urlencoded({ extended: false }));
What you claim to have "tried doing" is exactly what you wrote in the code that works "as expected" when you invoke it with curl.
The error you're getting doesn't appear to be related to any of the code you've shown us.
If you want to get the raw request, set handlers on request for the data and end events (and, of course, remove any invocations of express.bodyParser()). Note that the data events will occur in chunks, and that unless you set an encoding for the data event those chunks will be buffers, not strings.
You use the following code to log post data:
router.post("/users",function(req,res){
res.send(JSON.stringify(req.body, null, 4));
});