'body' not accessible in Express router post request - javascript

I'm using Express router functions to handle some POST requests.
Client.js
let data = {
endpoint: "Blah Blah";
};
return fetch('/api/get-preferences/', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
Server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.json());
class HTTPServer {
constructor(credentials, app) {
this.app = app;
this.specifyRoutes();
}
specifyRoutes() {
this.router = express.Router();
this.router.use((req, res, next) => this.jwtVerify(req, res, next));
this.app.use('/api', this.router);
this.router.post('/get-preferences', this.getPref);
}
jwtVerify(req, res, next) {
console.log(req.body); // This prints "undefined".
next();
}
}
I can't access the data that I sent from the client side on the server side in the jwtVerify function and once this is fixed, I would like to pass that data to the getPref function in the /get-preferences route.

Two issues here. First, update:
this.app.use(bodyParser.json());
Second:
this.app.use('/api', this.router);

Related

Get POST request body with express and fetch

I'm new to server-side development.
I'm trying to set up a node.js server that can receive posts.
My client-server code sends the post request:
function post(){
fetch('/clicked', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({a: 1, b: 'Text'})
})
.then(function(response){
if(response.ok){
console.log('POST success.');
return;
}
throw new Error('POST failed.');
})
.catch(function(error){
console.log(error);
});
}
And my Node.js server receives it:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/clicked', (req, res) => {
console.log(req.a);
console.log(req.b);
console.log(req.body);
res.sendStatus(201);
})
However, my server console logs all undefined.
What should I do to receive my POST request body?
Try setting up express.json() inside the app:
const express = require('express');
const app = express();
app.use(express.json())
app.post('/clicked', (req, res) => {
console.log(req.a);
console.log(req.b);
console.log(req.body);
res.sendStatus(201);
});
Add this before handling post request.
app.use(require('body-parser').json());
What body-parser does is, it will add all the information we pass to the API to the 'request.body' object.

Question about connecting React and NodeJS express

I tried to connect between React(Front End) and NodeJs(BackEnd) and NodeJS -> React(GET) worked well but React -> NodeJS(POST) always erred "POST http://localhost:3001/board/giveresult 500 (Internal Server Error)" and "Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0" I did all the way to solve that problem but I was stuck at that for a week. what is the problem?
// Method in React
setData() {
let data = {
id:this.state.contents.id, //contents is array in the state
write:this.state.contents.writer,
title:this.state.contents.title,
description:this.state.contents.description
}
fetch('http://localhost:3001/board/giveresult'
,{
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body:JSON.stringify(data)
})
.then (res => res.json())
.then (data => console.log(data));
}
//NodeJS Express
const express = require('express');
const app = express();
const receive = require('./routes/receive')
const giveResult = require('./routes/giveResult')
const port = process.env.PORT || 3001;
const cors = require('cors');
var bodyParser = require('body-parser');
app.use(cors());
app.use(bodyParser.json())
app.use('/board/giveresult', giveResult);
app.use('/board/receive', receive);
app.listen(port, function(){
console.log(`connected ${port} port!`);
});
//giveResult
var express = require('express');
const router = express.Router();
var mysql = require('mysql');
const dbconfig = require('../mysql.js');
const { Router } = require('express');
const connection = mysql.createConnection(dbconfig);
var bodyParser = require('body-parser');
router.post('/', function(req, res) {
if(err) throw err;
var post = req.body.id;
console.log(post)
res.send('suceess!!!!');
});
module.exports = router;
Try adding accept in your request header be like .
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}

Axios Post request from my react app to the express server giving error 500

I am trying to make a post request from my react app to the express server. On making the post request from postman works fine but when I make it from my react app It gives error 500 (Internal server error)
This is my client side code-
function signUpWithEmail(e,email,password,ConfirmPassword,userHandle) {
e.preventDefault();
let params = {
email: email,
password: password,
ConfirmPassword: ConfirmPassword,
userHandle: userHandle
}
let res = axios({
method: 'post',
url: 'http://localhost:3031/signUp/',
data : params,
headers: {
'Content-Type': 'application/json;charset=UTF-8',
'Access-Control-Allow-Origin': '*'
},
validateStatus: (status) => {
return true
},
})
.then(() => console.log('Created'))
.catch((err) => {
console.log(err.message)
})
This is my server code
`const functions = require('firebase-functions');
const express = require('express')
const app = express()
const port = 3031;
const cors = require('cors');
const { signup } = require('./server/users');
const { login, getAuthenticatedUser } = require('./server/users');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:3000/");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
app.use(cors())
app.use(bodyParser.json())
app.get('/', (req, res) => res.send('Hello World!'))
app.post('/signUp',cors(),signup);
app.post('/login', login);

Cannot post data from React Js to Node js

I am beginner use React Js and Node Js, I get a problem, I cannot post my data from React Js to Node Js, I have been looking for the way but failed all, I don't know why.
This is my complete code.
This is my react file 'member.js', run on port 3000 (http://localhost:3000/member).
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Member extends Component {
constructor() {
super();
this.state = { player: {} };
}
handleSubmit(e) {
e.preventDefault();
fetch('http://localhost:4000/player', {
mode: 'no-cors',
method: 'post',
headers: {
"Content-Type": "text/plain"
},
body: JSON.stringify({
number: 123,
name: "John",
position: "Andrew"
})
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log('Request failed', error)
});
}
render() {
return (
<div className="member-page">
<form>
<input type="submit" onClick={this.handleSubmit.bind(this)} />
</form>
</div>
)
}
}
export default Member;
and this is my node file 'player.js', run on port 4000 (http://localhost:4000/player).
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var app = express();
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
var player = req.body;
var query = connection.query('INSERT INTO player VALUES ?', player, function(err, result) {
// Neat!
});
res.end('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
I don't know where I do a mistake, please anyone correct my code either member.js or player.js.
Thank you very much for all the help.
I agree with #robertklep. I think problem is in var player = req.body;
Try:
Install body-parser npm package
npm i -S body-parser
Configure body-parser
var http = require('http');
var mysql = require('mysql');
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
//enable CORS
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();
});
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "react_1"
});
app.post('/player', (req, res) => {
var player = req.body;
var query = connection.query('INSERT INTO player VALUES ?', player, (error, results, fields) => {
if (error) throw error;
// Neat!
});
res.send('Success');
});
app.listen(4000, function() {
console.log('Example app listening on port 4000!');
});
const express = require('express')
var bodyParser = require('body-parser')
const app = express()
var router = express.Router();
router.use( bodyParser.json() ); // to support JSON-encoded bodies
router.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(5000, () => {
console.log('Example app listening on port 5000!')
})
app.use('/', router);
Try to Configure your node server like this
First install body-parser using :
npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
If you are passing string data then use
app.use(bodyParser.text());
Otherwise if you are passing data as Json then use
app.use(bodyParser.Json());
It should work in your case.

Passing Angular variable to Express backend through POST

req.body is always empty. I'm not sure what I'm doing wrong? I tried adding content-type headers as json but that didn't do anything either. Can someone lead me in the correct direction please? Thank you
EDIT: just for clarification purposes, my Angular frontend hits the backend function successfully, but req.body is empty. If I understand everything correctly, if I'm using the 'body-parser' library, it should be passed in through post through 'req.body'. I'm just not seeing that though and I'm not sure why.
EDIT2: I have the body parser code in my app.js but the backend routing in a index.js file, does that have anything to do with it?
EDIT3: app.js http://pastebin.com/9vNgf0Nd
index.js http://pastebin.com/icLa3e2X
ANGULAR FRONTEND
service.registerAccount = function(account) {
console.log(account); //account = { userName: 'test', password: 'hello' }
return $http({
method: 'POST',
url: '/register',
data: { account: account },
headers: {'Content-Type': 'application/json'}
});
}
BACKEND (app.js)
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
BACKEND (index.js)
var express = require('express');
var router = express.Router();
router.post('/register', function(req, res) {
console.log(req.body);
};
Please remove this line
app.use(bodyParser.urlencoded({ extended: true }))
Also,
app.use(bodyParser.json());
have to be called before app.use('/', routes);
And make sure to add Content-Type: application/json to the request header
What happens if you add the content type?
service.registerAccount = function(account) {
console.log(account); //account = { userName: 'test', password: 'hello' }
return $http({
method: 'POST',
url: '/register',
data: { account: account },
headers: {
'Content-Type': 'application/json'
}
});
}
Try this
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/register', function(req, res) {
console.log(req.body);
});
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)
});
and then execute this from prompt:
$ curl localhost:8081/register -v --data "{\"name\":\"test\",\"password\":\"hello\"}" --header "Content-Type: application/json"
this works for me!
There is nothing wrong in the UI code. Not sure what is router so you may try this or post the code for router.
Try this (this works for me) or you can also use your router:
app.post('/register', function (req, res) {
console.log(req.body);
res.send('welcome, ' + req.body.account.username)
});
You are missing:
var app = express();
app.use(router);
If you want to user routers refers to following example:
UPDATE with full code:
var express = require('express');
var router = express.Router();
var app = express();
app.use(router);
router.post('/register', function(req, res) {
console.log(req.body);
};
app.route('/register')
.post(function (req, res) {
console.log(req.body);
res.send('welcome, ' + req.body.account.username)
})

Categories

Resources