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");
});
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 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
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.
I am trying to build a simple Node.js app which will parse data passed to it as POST requests from my AngularJS app. Below is the code used in my AngularJS app and my Node.js app. Problem I am facing is that I've searched the web trying to find how to parse (data and header) information passed in POST requests but failed to find any example, so any help with an example of parsing (data and header) passed in POST requests will help me a lot. Thanks.
Note: I am using express 4.1.2, body-parser 1.8.0.
Node app:
var express = require('express');
var http = require('http');
var bodyParser = require('body-parser');
var app = express();
app.set('port', process.env.PORT || 3000);
app.use(bodyParser.json());
app.post('/', function (req, res) {
console.log(req.body);
res.send(200);
});
http.createServer(app).listen(app.get('port'), function(){
console.log('Server listening on port ' + app.get('port'));
});
POST request code
var deferred = $q.defer();
var dataObj = {};
dataObj.name = 'Chan';
dataObj.email_address = 'email#domain.com';
var myToken = '1234567890';
$http({ method:'POST',
url: '/',
data: dataObj,
headers: { 'Token' : myToken
}
}).success(function(data,status,headers,config){
deferred.resolve(data);
}).error(function(data,status,headers,config){
deferred.reject(status);
});
return deferred.promise;
If you're setting data to a plain js object, angular is interpreting that as a urlencoded form with the various keys and values in that object.
So there's two possible fixes here. One is to add something like app.use(bodyParser.urlencoded({ extended: false })); after app.use(bodyParser.json());
The second possible fix is to change your $http call to post JSON instead of urlencoded data. For that, change data: dataObj, to data: JSON.stringify(dataObj), and add 'Content-Type': 'application/json' to your headers so that it looks like this:
headers: {
'Token' : myToken,
'Content-Type': 'application/json'
}