I try to do API call from my react app to my nodejs server.
Here is the server code.
const express = require('express')
const app = express()
const port = 80
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use('/api', function (req, res) {
console.log(req.body)
})
app.listen(port)
And the react app code
function callServerWebhook(data) {
fetch('http://<IP>/api', {
method: 'POST',
headers: {'Content-Type': 'application/json', 'Accept': 'application/json'},
body: JSON.stringify({'username': 'foo', 'password':'bar'})
})
}
When i print the req.body, it's give me an empty object. What i'm doing wrong?
You need both bodyParser.json() and bodyParser.urlencoded() to correctly parse the data:
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
Related
I created a proxy on firebase using http-proxy-middleware.
It works on GET requests but does not pass the data I send via body in POST requests. I did some research and added the "onProxyReq" method to the options. This way it works when I send json body, but not when I send form data.
const functions = require("firebase-functions");
const express = require("express");
var bodyParser = require("body-parser");
const {
createProxyMiddleware,
fixRequestBody,
} = require("http-proxy-middleware");
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var restream = function (proxyReq, req, res, options) {
if (req.body) {
let bodyData = JSON.stringify(req.body);
proxyReq.setHeader("Content-Type", "application/json");
proxyReq.setHeader("Content-Length", Buffer.byteLength(bodyData));
proxyReq.write(bodyData);
}
};
app.use(
"/",
createProxyMiddleware({
target: "http://IPADDRESS:8080/api",
changeOrigin: true,
onProxyReq: restream,
bodyParser: false,
})
);
exports.api = functions.https.onRequest(app);
This code works with json body.
Changing "application/json" to "multipart/form-data" doesn't work.
All I want is to redirect the JWT token in the header and the FormData in the body.
What should be the best way for this?
Login.js - react component.
I printed the JSON.stringify(credentials) object and it is valid but when i print the req.body in the server it is empty.
//sending a post request to the server with the username and password inserted by the user.
async function loginUser(credentials) {
console.log(JSON.stringify(credentials));
return fetch('http://localhost:8080/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(credentials)
})
.then(response => {
console.log(response);
})
};
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
you have to use a middleware to parse the json body in the post request,
you have not used bodyParser.json() as middleware
below is your updated code
server.js
var express = require('express')
var bodyParser = require('body-parser')
var cors = require('cors')
var app = express()
app.use(cors());
// create application/json parser
app.use(bodyParser.json());
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: false }));
// POST /login gets urlencoded bodies
app.post('/login', function (req, res) {
console.log(req.body);
res.status(200).send('welcome, ' + req.body.username)
})
I have an express app at localhost:5000 and a react app at localhost:3000.
I am calling it via
fetch(`${backendUrl}/charge`, {
method: "POST",
mode: "no-cors",
headers: {
"Content-Type": "application/json"
},
body: {
stripeToken: token,
chargeAmount: this.state.donationAmount
}
})
And responding with
function route(req, res) {
console.log(req.body);
}
Server should be properly configured to work with CORS, but the body is still empty.
//configure env variables
require("dotenv").config();
//import packages
var express = require("express");
var bodyParser = require("body-parser");
var cors = require("cors");
//import route functions
const StripeRoute = require("./StripeRoute");
//setup app
const app = express();
const port = process.env.PORT || 5000;
//setup bodyparser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//Setup CORS
app.use(cors());
app.options("*", cors()); // include before other routes
//Connect functions to API routes
app.post("/charge", StripeRoute);
module.exports = app;
According to the documentation, the body option should be one of a few specific types, Object not being one of them.
Try using a JSON string:
body: JSON.stringify({
stripeToken: token,
chargeAmount: this.state.donationAmount
})
EDIT: because you're using no-cors, you can't set Content-Type application/json. Instead, you need to generate a URL-encoded string and set Content-Type to application/x-www-form-urlencoded (because no-cors will only work using "simple headers", as explained here and further).
when i post json data on node server, it leads to error
'Response to preflight request doest't pass access control check'
but when i post same request on php server it works .
browser console picture
can someone tell me why this not working in node.js but
when i tried to post data through postman on node server now no error it works.
postman picture
here is my nodeJS code
const express = require('express');
const app = express();
app.use(express.json());
app.post('/post', function(req, res){
res.header('Access-Control-Allow-Origin', '*');
res.send(req.body);
})
and this is request code that is send from browser
function callAjax(){
jQuery.ajax({
method: 'POST',
url:'http://localhost:3010/post',
"headers": {
"content-type": "application/json"
},
data: {
email:'fake#mail.com'
},
success: function(data){
console.log(data);
},
error: function(err){
console.log(err);
}
});
}
You have to use body-parser.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.post('/post', function(req, res){
res.setHeader('Access-Control-Allow-Origin', '*');
res.json(req.body);
});
use cors module first:-
npm install --save cors
var cors = require('cors')
app.use(cors())
var http = require('http');
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
var path = require('path');
var mysql = require('mysql');
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json({type: 'application/json'});
var cookieParser = require('cookie-parser');
var cors = require('cors');
app.use('*', cors());
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json({type: 'application/json'}));
app.use(cookieParser());
here is my client side code using jquery API
$.ajax({
url: "/checkIfAdmin",
type: 'GET',
data: JSON.stringify({'password': 'password', 'username': 'username'}),
crossDomain: true,
async: true,
cache: false,
contentType: "application/json; charset=utf-8",
processData: false,
success: function (data) {
// doing something
},
error: function(data){
// throw error here!
}
});
Body parser has been returning an empty body, being trying to fix this now for a while, on app route below
app.get('/checkIfAdmin', jsonParser, function(req, res){
console.log(req.body);
// Am getting an empty object ie {}
});
am getting { } (empty object)
please how do I fix this
It's get API. So, you will get the data in req.query.