I am trying to make some client-server program using express. But no matter what I try req.body is always empty. I have searched for solutions, but the main problem in most cases is that 'Content-Type' or app.use(bodyParser.json()); are missing. I have got both, but it still doesn't work.
Here is my server side:
const express = require('express');
const app = express();
const port = 5000;
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/', (req, res) => {
console.log(req.body);
res.send(req.body);
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Here is client side:
const promise = fetch('http://127.0.0.1:5000', {
mode: 'no-cors',
credentials: 'include',
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'Accept' : 'text/plain;charset=UTF-8',
},
method: 'POST',
body: JSON.stringify({x: 2, y:3}),
});
The problem is the mode: 'no-cors'. You won't be able to set the Accept and Context-Type headers.
Related
This post is hidden. You deleted this post 1 min ago.
Hi their are many questions related to the same topic but none of them solved my problem thats why asking new question
What I wanted to do is to send POST request from client side javascript to the Backend NodeJs
Client Side JS
const verifyOtp = async (otp) => {
const res = await fetch("http://127.0.0.1:3000/api/otpVerify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ otp: otp.value }),
});
const data = await res.json();
console.log(data);
}
Backend Node js
const verifyOtp = router.post("/api/otpVerify", (req, res, next) => {
const otp = req.body;
console.log("Otp recieved: ", otp);
console.log("Actual Otp: ", req.session.otp);
if (otp == req.session.otp) {
return res.json({ isVerified: true });
}
return res.json({ isVerified: false });
});
App.js File
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const session = require("express-session");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(
session({ secret: "cezisbest", resave: false, saveUninitialized: false })
);
app.use(express.static(path.join(__dirname + "public")));
app.set("view engine", "ejs");
app.set("views", "views");
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, application/json"
);
next();
});
app.use("/api", userRoutes);
app.listen(process.env.PORT);
what I am getting Backend Node js file is an empty object Please help me with this error
opt.value is having a value which it is getting from frontend
in client side JS
on browser chrome it is displaying an object
{isVerified:false}
because the backend is unable to get data
Please help me with this issue
You are not setting the req.session.otp value before calling /api/otpVerify. What is the reason you are using req.session?
req.session is basically gets cookies related information
Refer this:
Cannot access req.session variables in Express/NodeJS
I am trying to post the data from javascript to the express server using fetch, but the then part in the fetch is not executed and when I console log the req.body in app.js it prints "Body [object Object]". Please help me fix this fetch.
book.ejs
<script>
document.getElementsByClassName('submit_booking_btn')[0].addEventListener('submit',function(){
e.preventDefault();
fetch('/booking', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: JSON.stringify({
name: "John",
email: document.getElementById("myCalendar").value
})
}).then(function(response){ return response.json()})
.then(function(myJson){console.log(myJson);})
.catch(e=>{console.log(e);})
})
</script>
app.js
const express = require("express");
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.post("/booking",function(req,res){
console.log("Body "+ req.body);
res.render("home");
});
I have started with nodejs and have been trying to send data in the post api using axios but not getting it in the server side here is my setup
CLIENT
export default class App extends Component {
componentDidMount() {
const headers = {
'Content-Type': 'application/json',
'Authorization': 'JWT fefege...'
}
let data = { title: "abc", price: 20 }; // i am sending this data
axios
.post("http://localhost:5000/add-product", data, {
headers: headers,
})
.then((res) => console.log(res))
.catch((err) => console.log(err));
}
render() {
return (<div></div>);
}
}
SERVERS SIDE
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const app = express();
let cors = require("cors");
const productRoutes = require("./routes/product");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(productRoutes);
app.listen(5000)
products routes.js file
const express = require('express');
const productController = require('../controllers/product');
const router = express.Router();
router.post('/add-product', productController.addProduct);
module.exports=router
controller file
exports.addProduct = (req, res, next) => {
console.log(req.body) //gives me {} everytime
}
here eveytime i send an object from client side i see {} as console
Both my projects runs on localhost:3000 and 5000 respectively
Add
app.use(bodyParser.json());
I am trying to send an image from mobile (I took photo) and send to NodeJS from React without success.
Here is the piece of code.
ReactJS
const formData = new FormData();
formData.append("data", {
uri: imageURI,
name: "photo",
type: "image/jpg",
});
const resp = await fetch(URL + "/send", {
method: "POST",
body: formData,
headers: { "Content-Type": "multipart/form-data" }
}).then(async (res) => {
console.log(res);
});
And here is the NodeJS code:
const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 3000;
const server = require("http").createServer();
const fs = require('fs');
let multiparty = require('multiparty');
const app = express();
app.use(bodyParser.urlencoded({
extended: false,
type: 'multipart/form-data'
}));
//https://stackoverflow.com/questions/56748415/req-body-is-empty-in-node
app.post('/send', (request, response, next) => {
console.log(request.body);
console.log(request.body.data);
fs.writeFile('result.png', request.body, function(err) {
console.log('File created: result.png');
});
response.send('uploaded!')
});
//Start the Server
server.on("request", app);
server.listen(port, function() {
console.info(`PPT Server: ${server.address().port}`);
});
I am getting this error.
fs.js:1253
data : Buffer.from('' + data, options.encoding || 'utf8');
^
TypeError: Cannot convert object to primitive value
at writeFd (fs.js:1253:29)
at fs.js:1247:7
at FSReqCallback.oncomplete (fs.js:146:23)
How can I be able to save the uploaded image?
I'm trying to use fetch() to post to another Node.js server I am running. When I take out the headers, my console prints '{}'. When I keep them in, nothing is printed when I call the function.
I have tried using curl and I receive '{}' as well.
//Server.js (what I am trying to POST to)
var express = require('express');
var app = express();
var PORT = 4000;
app.use(express.json());
app.post('/', function (req, res) {
console.log(req.body);
})
app.listen(PORT, function () {
console.log('server running on port: ' + PORT);
})
//Post function (this is inside a separate React component which will perform the POST)
postContents() {
var data = { username: 'example' };
fetch('http://localhost:4000/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => response.json())
.catch(error => console.error('Error:', error))
.then(response => console.log('Success:', JSON.stringify(response)));
}
You have to use the body-parser as a middleware for your express server.
const express = require('express');
const app = express();
const PORT = 4000;
const bodyParser = require('body-parser');
app.use(bodyParser.json());
without headers and with headers the result is different
the URL is fully qualified with host and port
These two points suggest you are making a cross origin request.
The solution is to have the server
accept and handle OPTIONS requests when required
issue CORS headers in the response