request.body returning empty object - javascript

My request.body is returning an empty object in express 4.17.1.
It works fine on postman, but when I try consuming it at the frontend using javascript I get an empty object, even when I console.log it
Below is my code:
/////Express backend
const express = require('express');
const cors = require('cors');
const app = express();
app.use(express.json());
app.use(cors());
////React frontend
const myData = {
_id: "616a4663c3086a539a8c3dcc",
type: "describe_yourself",
name: "white"
}
React.useEffect( () => {
fetch('http://localhost:9000/test', {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify(myData)
}).then(response => response.json())
.then(data => console.log(data))
}, [])
I am not using body-parser because it is deprecated.
I will really appreciate anyone that can help me. thanks in advance

Related

unable to get values for react js in node

I want to send values from react to node. I am using fetch but I am not getting. Here's the code:
React Code:
const values = {email,pass}
const data = {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(values),
}
fetch('http://localhost:8000/', data)
.then(res => res.json())
.then(data => console.log(data))
Node Code:
const express = require("express")
const cors = require('cors')
const app = express()
app.use(
cors({
origin: '*'
})
)
app.listen(8000, 'localhost')
app.post('/' , ( req, res ) => {
console.log(req.body)
} )
When I am visiting to this http://localhost:8000/
i am getting an error
Cannot GET /
use json body parser:
app.use(express.json());
You need express to use json body parser:
app.use(express.json());
Additionally you are not sending any response from your Node Server to the client,
try something like this this:
app.post('/' , ( req, res ) => {
console.log(req.body)
const data = JSON.stringify(req.body)
console.log(data)
res.status(200).json({data: data});
})

How can I receive a json in express server

I need to receive a JSON from my front in React. But the JSON comes to me in a strange way (an object with the data in string), I don't know how to return it to type object again.
I send this.
const data = {
email: 'emailc#email.com',
password: 'test'
}
const options = {
method: 'POST',
body: JSON.stringify(data),
mode: 'no-cors',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
const onsubmit = (e) => {
//evitamos que se haga la peticion en automatico
e.preventDefault();
fetch('http://localhost:3001/user/signin',options)
.then(res => res.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', response));
console.log('send on submit');
}
and I get this on the express server:
[Object: null prototype] {
'{"email":"emailc#email.com","password":"test"}': ''
}
My server is configured in this way:
const express = require('express');
const app = express();
const morgan = require('morgan');
const cors = require('cors');
const {mongoose} = require('./src/database/connection')
const Parser = require("body-parser").urlencoded({ extended: false });
//config
app.set('port', process.env.PORT || 3001);
//middlewares
app.use(morgan('dev'));
app.use(Parser);
app.use(cors()); //accepts connection from all directions
//Routes
app.use(require('./src/test'));
app.use(require('./src/routes/users'));
//Server
app.listen(app.get('port'), (req, res) => {
console.log(`Server on port ${app.get('port')}`);
})
I think I have misconfigured the body-parser, please help, it is my first API.
'Content-Type': 'application/x-www-form-urlencoded'
If you tell the server you are sending Form Encoded data then it is going to try to parse what you send as Form Encoded data.
Don't lie.
If you are sending JSON, say so:
'Content-Type': 'application/json'
const Parser = require("body-parser").urlencoded({ extended: false });
You also need a body parser that supports JSON.
const Parser = require("body-parser").json();
But Express has a built-in body parser and variable names starting with capital letters are traditionally reserved for constructor functions / classes.
const parser = express.json();
Aside:
mode: 'no-cors'
If you are making a cross-origin request then that will break it.
If you are making a same-origin request then that will do nothing.
Remove it.

Express js request body is not excatcly i want

Im working on simple app that allows you to register new user. I managed to create fetch POST request and catch it with express app.post method. It works but the value that req.body is retruning is not plain object but something more that I want.
It's literally returning something like this : { '{"login":"fff","password":"sss"}': '' }
But I want it to be just sth like this: {"login":"fff","password":"sss"}
Here is my client side code
function eventListener() {
const formSubmit = document.querySelector('.register-form');
const newUser = new Register();
formSubmit.addEventListener('submit', (e) => {
e.preventDefault();
newUser.checkInputs();
const form = e.target;
const formData = new FormData(form)
const userData = {
login: formData.get('login'),
password: formData.get('password'),
}
console.log(userData);
fetch('/register', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: JSON.stringify(userData)
})
.then(response => {
console.log(response);
})
})
}
document.addEventListener('DOMContentLoaded', eventListener)
And here is server code
const express = require('express');
const path = require('path');
const app = express();
app.use(express.json())
app.use(express.urlencoded({
extended: true
}))
app.use(express.static('static'))
app.post('/register', (req, res) => {
console.log('ok');
console.log(req.body);
res.end();
})
app.listen(process.env.PORT || 5000, () => {
console.log('running...');
})
Don't lie to the server:
'Content-Type': 'application/x-www-form-urlencoded'
You are sending JSON.
By telling the server you are NOT sending JSON, you are confusing it.
It is trying to parse it as application/x-www-form-urlencoded
Tell it you are sending JSON:
'Content-Type': 'application/json'

Cannot post data from react to nodejs using fetch

I am using fetch to post data from react side to nodejs (both of which are running in my localhost) so what i am doing is
let formData = new FormData();
formData.append("agent_name", this.state.agentName);
formData.append("agent_email", this.state.agentEmail);
formData.append("agent_phone", this.state.agentPhone);
formData.append("agent_id", this.state.agentID);
formData.append("agent_password", this.state.agentPassword);
formData.append("state", this.state.selectedState);
formData.append("city", this.state.selectedCity);
formData.append("file", this.state.file);
formData.append("imageurl", this.state.imageUrl);
fetch("http://localhost:4000/add_delivery_agent", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((responsejson) => {
console.log(responsejson);
});
and then on server side i did
exports.addDeliveryAgent = async (req, res, next) => {
let data = req.body;
console.log(data);
}
};
but console.log(data) gives me empty object always, what am i doing wrong here ?
Also the data gets posted via axios but i want it via fetch !
App.js config is
const express = require("express");
const bodyparser = require("body-parser");
const app = express();
const mongoconnect = require("./utils/database").mongoconnect;
const path = require("path");
var cors = require("cors");
// const adminUserRoute = require("./routes/admin/user/user.js");
const adminDeliveryAgentRoute = require("./routes/admin/deliveryAgent/deliveryAgent");
const user = require("./routes/admin/user/user.js");
app.use(express.urlencoded());
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
app.use(cors());
app.use("/tfd/controlcenter/", express.static(path.join(__dirname, "/build")));
// app.use(adminUserRoute);
app.use(adminDeliveryAgentRoute);
app.use(user);
mongoconnect(() => {
app.listen(4000, () => {
console.log("running 4000");
});
});
try adding Content-Type header
fetch("http://localhost:4000/add_delivery_agent", {
method: "POST",
body: formData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
// or
// 'Content-Type': multipart/form-data
},
})
Don't use form data instead use plain object as bodyparser doesn't support multipart/form-data which is what form data uses
formData={}
formData.agent_name=this.state.agentName;
formData.agent_email=this.state.agentEmail;
//..
formData.imageurl=this.state.imageUrl;
fetch("http://localhost:4000/add_delivery_agent", {
method: "POST",
body: formData,
})
.then((response) => response.json())
.then((responsejson) => {
console.log(responsejson);
});

How can I send the serve response data from a fetch API to client?

Having a json object,I made an API call using fetch API and I got a response with the expected resuts. How can I send the results to the client, so as to be able to display them in the interface? I used express module from Node.js.
const fetch = require("node-fetch");
const express = require("express");
var bodyParser = require('body-parser');
const app = express();
app.post('/', (req, res) => {
res.sendStatus(200);
jsonBody = JSON.parse(fs.readFileSync("./resources/jsonBody.json", {
encoding: 'utf8'
}));
function results() {
fetch(url, {
method: 'POST',
body: JSON.stringify(jsonBody),
headers: {
"Authorization": "Bearer " + predictionKey,
"Content-Type": "application/json"
},
}).then(response => response.json()).then(response =>
console.log(response.Results.output1.value.Values));
}
results()
})
});
The client side post function:
function postMessage(message){
$.post("http://localhost:8000",message);
}
This is the response of the api call on the server
[ [ '1008', '0', '1' ],
[ '1079', '1', '3' ],
[ '1022', '2', '3' ] ]
and I want to display these values in the interface (on client)
Your variable url used in the fetch is not defined anywhere, so I have to assume you have a global variable elsewhere to the API you are calling.
If so, then you are doing this out of sequence - you are sending an empty 200 OK then fetching the jsonBody (which is another global var, maybe unintentionally) but then never using those results.
Try rearranging like so:
const fetch = require("node-fetch");
const express = require("express");
var bodyParser = require('body-parser');
const app = express();
app.post('/', (req, res) => {
res.sendStatus(200);
var jsonBody = JSON.parse(fs.readFileSync("./resources/jsonBody.json", {
encoding: 'utf8'
}));
fetch(url, {
method: 'POST',
body: JSON.stringify(jsonBody),
headers: {
"Authorization": "Bearer " + predictionKey,
"Content-Type": "application/json"
},
}).then(response => response.json()).then(response => {
console.log(response.Results.output1.value.Values);
res.json(response.Results.output1.value.Values); // or whatever you want from response
});
});

Categories

Resources