Sending data from javascript/html page to Express NodeJS server

走远了吗. 提交于 2019-12-07 15:50:26

req is an object full of stuff that comes with every request. You need to get body of your request. This might help you: How to retrieve POST query parameters?

But because there's not much client-side JavaScript i ust ask: Have you specified you want to POST this?

Try do it like here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send ...and when you use xhr.setRequestHeader("Content-Type", "application/json") you probably don't need to stringify this.

First of all on the client side do this..

var send = { "name":"John", "age":30, "car":null };
var sendString = JSON.stringify(send);
alert(sendString);
xhttp.send(send);

Then on the server side you need to add a middleware that will populate the body parameter in your request object.

var express=require("express");
var bodyParser=require("body-parser");

var app=express();

// Process application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({extended: true}))

// Process application/json
app.use(bodyParser.json());

app.post('/createEmp', function(req, res){  
//now req.body will be populated with the object you sent
console.log(req.body.name); //prints john
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!