I have a very simple node.js server:
const express = require("express");
const app = express();
app.post("/searcharea", (req, res, next) => {
console.log("SEARCH AREA2");
console.log(req.body);
res.status(200).send({ok:true});
});
app.listen(3000, () => {
console.log("Server running on port 3000")
});
However when I use curl and send data to the server I get an undefined as the req.body. Here is my curl statement when testing.
curl --header "Content-Type: application/json"
--request POST
--data '{"username":"search":"here"}'
http://localhost:3000/searcharea
Any guidance would be appreciated.
I am not sure about this data structure : '{"username":"search":"here"}', but to ingest json data from an express server you are required to use the json middleware like this
const express = require("express");
const app = express();
//!Important
app.use(express.json());
app.post("/searcharea", (req, res, next) => {
console.log("SEARCH AREA2");
console.log(req.body);
res.status(200).send({ok:true});
});
app.listen(3000, () => {
console.log("Server running on port 3000")
});
By default, req.body will be undefined. You need to include some sort of middleware to parse the incoming body of the POST request. Express.js packages this with it in v4.x and above. The included one handles most POST bodies but does not handle multipart requests. You'll need something like multer for that Change your code to this:
const express = require("express");
const app = express();
// parse JSON request body
app.use(express.json());
app.post("/searcharea", (req, res, next) => {
console.log("SEARCH AREA2");
console.log(req.body);
res.status(200).send({ok:true});
});
app.listen(3000, () => {
console.log("Server running on port 3000")
});
Related
I am trying to learn node js. I am tryng to put a post request from axios by frontend but node js is responding with empty object.
Here is the code
node js
var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
console.log("Got a GET request for the homepage");
res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
console.log(req.body);
res.send("Hello GET");
});
var server = app.listen(8081, function () {
var host = server.address().address;
var port = server.address().port;
console.log("Example app listening at http://%s:%s", host, port);
});
frontend
axios.post("http://localhost:8081/", { body: "dan" })
.then((e) => console.log(e))
The response is an empty object.
What should I do?
By default your axios code:
axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))
will send the body of the POST request as JSON. Quoted directly from the axios doc.
By default, axios serializes JavaScript objects to JSON
So, you need JSON middleware on your Express server to read and parse that JSON body. Without middleware that is looking for that specific content-type, the body of the POST request will not be read or parsed and req.body will remain empty.
app.post('/', express.json(), function (req, res) {
console.log(req.body);
res.send('Hello POST');
});
Note, there is no need to separately load the body-parser module as it is built-in to Express.
Or, if you want the request to be sent as application/x-www-form-urlencoded content-type, then you would need to encode the data that way and send it as the data in your axios request and set the content-type appropriately.
These request bodies can be handled by the express.urlencoded() middleware in the same way as express.json().
You should use bodyParser.json(), to get the data sent in req.body.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
We should parse request body before access it using middleware in the following way
app.use(bodyParser.json());
I've been trying to use body-parser but it's deprecated so I'm doing this
var express = require('express')
var app = express()
app.use(express.static(__dirname))
app.use(
express.urlencoded({
extended: true
})
)
app.use(express.json())
app.post('/send-message', (req, res) => {
console.log('request', req.body);
res.sendStatus(200)
})
var server = app.listen(3000, () => {
console.log('server is listening on port', server.address().port)
})
And send post request from Postman
But in the console I get
server is listening on port 3000
request {}
Why request is empty? and how to catch it correctly?
select json from the dropdown menu where text is written, this will set the content-type header to application/json
text to json
I spend so much time looking at this.. I am just following udemy tutorial where instructor used exactly below.. BUT when I run it, req.body is empty EVEN though I am sending it from source(I tried from both nodeman and insomnia). I am just posting { "name":"test" }... and it's not getting the req.body...
I console logged just req and do not see the parm 'body'... Can someone please throw me some light here? SO furstrated
const express = require('express');
const app = express();
const port = 8002;
app.post('/', (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`port : ${port}`);
})
Try using body-parser for your req.body.
First install the dependency npm install body-parser and then try executing the below code:
const app = express();
const bodyParser= require('body-parser')
const port = 8002;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.post('/', (req, res) => {
console.log(req.body);
});
app.listen(port, () => {
console.log(`port : ${port}`);
})
For more documentation refer: body-parser-documentation
I'm learning how to build a RESTful api with Node and Express, and I am having an issue with this https request. I am trying to make a GET request to Scryfall's api (documentation here: https://scryfall.com/docs/api), but whenever I run my server and check the browser I get a message stating
"localhost didn’t send any data. ERR_EMPTY_RESPONSE".
As I'm new to using Node and Express, I'm not really sure what I am doing wrong. Here is the code for my server.js and app.js files.
//server.js
const https = require('https');
const app = require('./backend/app');
const port = process.env.PORT || '3000';
app.set('port', port);
const server = https.createServer(app); //pass the express app to the server
server.listen(port);
and
//app.js
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('https://api.scryfall.com/cards/named?fuzzy=aust+com', (req, res, next) => {
res.send('${res.body.name} is the name of the card!');
});
module.exports = app;
Any help would be greatly appreciated! Thanks in advance!
👨🏫 For an example, you can do it with this code below 👇:
const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use((req, res, next) => {
console.log('This is the first middleware');
next();
});
app.get('/', async (req, res, next) => {
try {
const result = await axios.get('https://api.scryfall.com/cards/named?fuzzy=aust+com');
res.status(200).send(result.data);
}catch(ex) {
console.log(ex.message);
}
});
app.listen(3000, () => {
console.log('Server is up');
})
💡 From the code above, you can call the endpoint: localhost:3000 and than you will get the result.
I hope it's can help you 🙏.
You can easily make a get request like this.
const express = require('express');
const app = express();
const port = 8080;
const bodyParser = require('body-parser');
//Expect a JSON body
app.use(bodyParser.json({
limit: '50mb' //Request size - 50MB
}));
app.get('/test', (req, res, next) => {
// do whatever you need here
res.status(200).send("ok");
});
app.listen(port, function () {
console.log(`Server is running.Point your browser to: http://localhost:${port}`)
});
I created a simple server using expressjs and have post method but I got strange response to post article and I don't know why it happened. Could anyone mind helping me?
my expected is a JSON format.
Here is my app.js file
const express = require('express');
const mongoose = require('mongoose');
const articleModel = require('./models/article');
const bodyParser = require('body-parser');
enter code here
const db = mongoose.connect('mongodb://0.0.0.0:27017/bbs-api');
const app = express();
const port = process.env.PORT || 3000;
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended:true}));
// support parsing of application/json type post data
app.use(bodyParser.json());
const bbsRouter = express.Router();
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.body);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.body);
});
app.use('/api', bbsRouter);
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log('Example app listening on port 8000!'))
My postman. I log request body out but it is not as my expectation.
if you are sending form data(application/x-www-form-urlencoded) the you can do
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.params);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.params);
});
You're sending the wrong request body via postman, your body should be JSON format, not form data
Try removing body-parser and use middlewares directly from express and set urlencoded to false:
app.use(express.urlencoded({extended:false}));
// support parsing of application/json type post data
app.use(express.json());
See here urlencoded option documentation