I tried everything to get my request body in POST method. I'm using postman with raw and form-data mode. Tried calling this API from react too nothing works. console.log(req.body) prints blank. {}
do let me know what I am missing.
const express = require('express');
const app = express();
const bodyParser = require("body-parser");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
const port = 9000
const enableWs = require('express-ws');
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/', (req, res) => {
console.log(req.body);
res.send('Hello World!')
});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
});
Now, I recreated your app, and it actually works.
I am using insomnia to test your api.
To the route "/" with Post, and some JSON.
Then in the Console.log I get the request body.
Console.log
Maybe you are testing incorrectly? Please get back to me if there is any question.
My guess is that you are not passing anything in your POST request, hence the empty body.
Be sure to specify Content-Type to application/json in postman's request headers.
In order for body-parser to parse req.body from JSON, your request must specify that the content is, in fact, JSON. Otherwise, it will not parse it; resulting in your blank req.body.
fetch('http://localhost:9000', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: 'hi',
}),
})
Related
So i am sending a POST request to a nodeJS app, my request in Angular looks like this:
export class SearchComponent {
constructor(private http: HttpClient) {}
newWord = '';
keyword = '';
onClick() {
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http
.post('http://localhost:3000/search', JSON.stringify(this.keyword), {
responseType: 'text',
headers: headers,
})
.subscribe((data) => {
this.newWord = data;
});
}
}
When i try to console.log the request i get an Unexpected token " in JSON at position 0 error even though i tried all the solutions i could find on stackoverflow this is how my NodeJS app is set and the error:
const bodyParser = require("body-parser");
const express = require("express");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.all("/*", function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS");
res.header(
"Access-Control-Allow-Headers",
"Content-Type, Authorization, Content-Length, X-Requested-With"
);
next();
});
app.listen(3000, () => {
console.log("Server is running on port 3000");
});
app.post("/search", (req, res) => {
res.send(req.body);
});
The error i get is this:
SyntaxError: Unexpected token " in JSON at position 0
at JSON.parse (<anonymous>)....
Note that the this.keyword gets its value from a input field if i dont use JSON.stringify no error is happening but the req variable is "undefined".
Assuming you are asking how to get back the data. I'm not sure if this will work, but you can give it a try:
Under comments, see that you mean this.keyword. Here is the change I would make
going by axis format, this may be incorrect
.post('http://localhost:3000/search', JSON.stringify(this.keyword), {
responseType: 'text',
headers: headers,
})
instead, try:
.post('http://localhost:3000/search', {
keyword: this.keyword, // changed this
responseType: 'text',
headers: headers,
})
also in your server, you can change to this:
const app = express();
app.use(express.json())
app.use(express.text())
app.use(express.urlencoded({ extended: true }))
(body parser included in express now)
new to the mern stack (have never used Angular) so kind of iffy but hopefully that can help
I've been working on a project with express, and have a post request set up. However, it returns an empty body on the response, but it appears to be working otherwise.
Here's the server:
const express = require('express');
const app = express();
const http = require('http').Server(app);
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.raw());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
app.use("/public", express.static(__dirname + "/public"));
http.listen(8080, '0.0.0.0' , function() {
console.log('listening on localhost:8080');
});
app.post('/form', (req, res) => {
console.log(req.body);
res.end('bla bla bla');
// I've also tried res.json and res.send
});
And here's the client:
fetch("/form", {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({bla: "bla"})}).then((thing) => {
console.log(thing);
console.log(thing.json());
console.log(thing.body);
});
This seems like it should work, but instead it returns this object:
Response
body: (...)
bodyUsed: true
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost:8080/form"
[[Prototype]]: Response
I can't seem to find where the error lies, or even whether it's working and I just don't know how to get the data from it.
I've figured it out! It turns out that my code was working all along, it's just that I had messed up the fetch request. What I should have done client-side was:
fetch("/form", {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify({bla: "bla"})})
.then(res => res.json())
.then(data => console.log(data));
I was missing the second .then() and that was throwing it off.
I am having an issue with sending data from an Axios post request to my ExpressJS post route. When I try to read the data sent on the post route it shows as undefined. This is my Axios post:
axios.post('http://localhost:3000/temps/heating', {
messageType: 'heating',
toggle: 'on'
}).then(res => {
console.log(res);
}).catch(e => {
console.log(e)
})
and this is my ExpressJS Post route below. I have tried to use req.params req.body & req.messageType
routes.post('/heating', (req, res, next) => {
const messageType = req.data;
console.log(messageType);
})
I thought that because Axios is sending "data" I request data on the NodeJS post route?
Thanks
In your express app make sure to use body-parser: https://expressjs.com/en/resources/middleware/body-parser.html
const bodyParser = require('body-parser');
app.use(bodyParser.json());
In your route you should then be able to access req.body.messageType:
routes.post('/heating', (req, res, next) => {
const messageType = req.body.messageType;
console.log(messageType);
})
It looks like you are using express.js in your node app. If that's the case, it would be const messageType = req.body.messageType;
I am trying to execute a post request using axios but the req.body is showing empty object . Here is my code :
const postData = {
tournamentId: tournamentId,
category: category,
contestantId: contestantId,
};
axios.post(`${process.env.URL}/joinTournament`, postData)
.then((res) => {
console.log(`Status: ${res.status}`);
console.log("Body: ", res.data);
})
.catch((err) => {
console.error(err);
});
Try a few things like test your backend logic with Postman (An API Development Tool). Then try to console log your request in backend to confirm the request reaching is correct.
If all that checkout turn to your libraries if you are using expressjs try to use a middleware like body-parser and cors to send back responses
The Code being something like
For Cors
//Cors
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(69, function () {
console.log('CORS-enabled web server listening on port 80')
})
For Body-parser
//body-parser
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' })
Might as well setup a checker block where you'd check that if the request is missing some necessary info to send back some understandable response.
I have solved this issue using qs and calling stringify method on postData . Here is my solution :
const qs = require("qs");
const postData = {
tournamentId: tournamentId,
category: category,
contestantId: contestantId,
};
axios.post(`${process.env.URL}/joinTournament`, qs.stringify(postData))
.then((res) => {
console.log(`Status: ${res.status}`);
console.log("Body: ", res.data);
})
.catch((err) => {
console.error(err);
});
if your server works very well with request from postman and every things is Ok, you can do like this, without third party module
I send a post request in my vue component file :
axios.post('/add-couple', {
word_key: this.word_key,
word_value: this.word_value
})
.then((response) => {
this.word_key = ''
this.word_value = ''
})
And handle that in dev-server.js(using express):
app.post('/add-couple', (req,res) => {
newCouple(req.word_key,req.word_value)
console.log(req.word_key,req.word_value) //undefined undefined
res.end()
})
So, i want to use word_key and word_value vars, but cant, because they're both undefined. What am i doing wrong?
You should use body-parser middleware and req.boby object to get sent params:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/add-couple', (req, res) => {
console.log(req.body.word_key, req.body.word_value);
...
});