NodeJs unable catch the data post from ReactJs form - node.js

I using ReactJs build the form for user key in the details. I also using NodeJs to handle the post data from the React. But the NodeJs seem like did not catched the data.
This is react event handling
handleSave(e){
let caseData=this.state.caseInfo
let url = 'http://localhost:8080'
console.log(caseData)
fetch(url,{
method:"POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
data: JSON.stringify({caseInfo: caseData}),
})
}
This is NodeJS
var http = require('http');
var url = require('url');
var bodyParser = require('body-parser')
var express = require('express')
var app = express()
http.createServer(function(req,res){
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
app.use(function (req, res){
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
console.log(JSON.stringify(req.body));
})
}).listen(8080);
I expect the data from the React can using post method to the Node and display the data in console log. However in the console of the server it display nothing.

It seems like you're not using express in the standard way. I'd change it to be more like the following...
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.json({ posted: req.body });
console.log(JSON.stringify(req.body));
});
app.listen(8080);
And probably just get rid of the call to http.createServer altogether.
--
Check out the docs for more routing examples: https://expressjs.com/en/starter/basic-routing.html

If you are serving your react app from another server, for instance localhost:3000 (as used by create react app), and you are trying to make api calls to a server on localhost:8080 you are going to get CORS errors because the browser sees these as two different domains. To get started, you can look at the docs here: https://expressjs.com/en/resources/middleware/cors.html
But you will probably have to npm install cors where your server lives and use something like the following:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use(bodyParser.json());
app.post('/', (req, res) => {
res.json({ posted: req.body });
console.log(JSON.stringify(req.body));
});
app.listen(8080);

Related

axios post request from frontend not recieving in node js backend

I am trying to learn node js. I am tryng to put a post request from axios by frontend but node js is responding with empty object.
Here is the code
node js
var express = require("express");
var app = express();
var cors = require("cors");
app.use(cors());
var bodyParser = require("body-parser");
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// This responds with "Hello World" on the homepage
app.get("/", function (req, res) {
console.log("Got a GET request for the homepage");
res.send("Hello GET");
});
app.post("/", urlencodedParser, function (req, res) {
console.log(req.body);
res.send("Hello GET");
});
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);
});
frontend
axios.post("http://localhost:8081/", { body: "dan" })
.then((e) => console.log(e))
The response is an empty object.
What should I do?
By default your axios code:
axios.post("http://localhost:8081/",{body:"dan"}).then((e) => console.log(e))
will send the body of the POST request as JSON. Quoted directly from the axios doc.
By default, axios serializes JavaScript objects to JSON
So, you need JSON middleware on your Express server to read and parse that JSON body. Without middleware that is looking for that specific content-type, the body of the POST request will not be read or parsed and req.body will remain empty.
app.post('/', express.json(), function (req, res) {
console.log(req.body);
res.send('Hello POST');
});
Note, there is no need to separately load the body-parser module as it is built-in to Express.
Or, if you want the request to be sent as application/x-www-form-urlencoded content-type, then you would need to encode the data that way and send it as the data in your axios request and set the content-type appropriately.
These request bodies can be handled by the express.urlencoded() middleware in the same way as express.json().
You should use bodyParser.json(), to get the data sent in req.body.
var bodyParser = require('body-parser');
app.use(bodyParser.json());
We should parse request body before access it using middleware in the following way
app.use(bodyParser.json());

How to send response from a post request in node.js?

I am trying to send response from post requests and on internet I have seen I have to use res.end but it does not seem to work in my case. I have done post requests in the past succesfully but now I need to do them without loading the website, so it has to be asynchronous for each post request.
This is what I have:
Game.js:
textModalContent1.addEventListener("click", () => {
//Ask for username
let username = prompt("Enter your new username");
$.post("/addUser",{username: username}, function(data){ //I use jQuery for post requests
console.log(data);
});
});
index.js:
const express = require('express');
const app = express();
app.use('/assets', express.static('./assets/'));
var bodyParser = require('body-parser')
app.use( bodyParser.json() );
app.use(bodyParser.urlencoded({
extended: true
}));
app.get('/', function (req, res) {
res.render('./index.ejs', {});
});
app.post('/addUser', function(req, res) {
//console.log(req.body.username)
res.end("hello"); //this should send "hello" to the client
});
app.listen(process.env.PORT || 14532);
Each time I enter a username, should appear "hello" on my web browser console but it does not.
What am I doing wrong?

Why REQ.BODY is always empty?

I know there are a lot of answer already marked as a working solution, but I can't make it work in my case, so please don't marked it as already answered, this is my scenario:
AJAX CLIENT SIDE
var data ={};
data.test="ciaozio";
$.ajax({
url: 'http://localhost:5000/dir',
method: "POST",
contentType: "application/json",
data: JSON.stringify(data),
header: "Access-Control-Allow-Origin",
success: function(data){
console.log(data);
},
error: function(data) {
console.log("error");
}
});
NODEJS SERVER-SIDE
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var router = express.Router();
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.use(bodyParser.json()); // support json encoded bodies
app.use('/', router);
app.post('/dir', function (req, res) {
console.log(req.body);
res.end("Ok");
})
var server = app.listen(5000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
CONSOLE-OUTPUT
Example app listening at http://:::5000
{}
CLIENT-SIDE CONSOLE OUTPUT
Access to XMLHttpRequest at 'http://localhost:5000/dir' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index.js:29 error
jquery-3.4.1.min.js:2 POST http://localhost:5000/dir net::ERR_FAILED
You need to add and configure CORS to your request.
Steps:
1.Install cors npm package
npm install cors
2.Node server-side snippt
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
//app.use(...) lines;
// app.post(..) lines;

why post json data not receive in node.js?

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())

BodyParser data is undefined after AJAX call

The body parser body is {}. I've already done research and made sure that my ajax data key is set correctly as well as make sure the middleware is set up correctly as well. Here is my frontend ajax call
$.ajax({
type:"GET",
url:"/api",
data: {course:"MATH-226"},
success: function(data){ alert(data);}
});
And here is my backend server.js file:
'use strict'
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const alg = require('./app/algorithm.js');
const app = express();
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.get('/api', (req, res) => {
console.log(req.body);
alg.create(req.body.course, answer => res.send(answer));
});
let server = app.listen(3000, () => {
let host = server.address().address;
let port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You are using a GET request, so it's probably not being sent. If you need to send something, you can attach it as a header or include it in the query string of the url. If you want to send data, I would use a POST request.
Check out this article
How to send data in request body with a GET when using jQuery $.ajax()

Resources