Express无法从客户端正确获取json数据

express can't get json data correctly from client

本文关键字:获取 json 数据 客户端 Express      更新时间:2023-09-26

这是我的客户端ajax代码:

var sendData = JSON.stringify({
        name: document.forms["token"].name.value,
        password:document.forms["token"].password.value
    });
$.ajax({
    url:'http://localhost:8088/log/',
    type:'POST',
    contentType:'application/json',
    data: sendData,
    dataType:"json"
})

,这里是我的节点服务器代码:

const http = require('http');
const express = require("express");
const jwt = require('jwt-simple');
const moment = require('moment');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
var expires = moment().add(7,'days').valueOf();
var token;
app.set("jwtTokenSecret","luo");
app.use(bodyParser.urlencoded({ extended: false }));
app.all("/log",function(req,res){
    var name = req.body.name;
    var password = req.body.password;
    console.log(name,password)
    ...
}

我发现节点服务器上的名称和密码都没有定义,客户端上的json数据是正确的。我已经尝试了很多方法来解决它,但是我不能,我需要你的帮助,谢谢。

$.ajax已经序列化了数据,因此,如果您已经将dataType设置为'json',则没有必要使用JSON.stringify

在我的例子中,我让ajax调用像这样的东西。

从客户端进行ajax调用:

function _sendData(){
  var host= 'localhost'; //or you can set your host by your choice. 
  $.post(host+'/post',$('#horizontalForm').serialize(),function(response){
    // respose
  });
}

node.js服务器端代码给出如下,

var qs = require('querystring');
app.post('/post',function(req,res){
        if(req.method=='POST'){
            var body='';
            req.on('data',function(data){
                body+=data;
                console.log("before proccess = "+body);
                if (body.length > 1e6) {
                // FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
                request.connection.destroy();
            }
            })
            req.on('end',function(){
                var post = qs.parse(body);
                console.log(post.user);
                console.log(post.message);

            })
        }
})

和HTML部分就像

<form method="POST" action="/post" id="horizontalForm">
  <p class="lead">
    <input type="text" name="user" value="testUser" id="userId"/>
    <div>
    <input type="text"  name="message" id="messageId"/>
    <input type="button" value="Send" class="btn btn-lg btn-default" id="getData" onclick="_sendData();"/>
    </div>
  </p>
</form>

N。B:安装查询字符串可以运行命令npm install querystring --save
不要忘记在你的html中包含jquery.jsajax

使用console.log('values',document.forms["token"])表达式检查document.forms["token"]是否包含namepassword

如果有值,

然后调用api

var sendData = {
    name: document.forms["token"].name.value,
    password: document.forms["token"].password.value
};
var saveData = $.ajax({
    url: 'http://localhost:8088/log/',
    type: 'POST',
    contentType: 'application/json',
    data: sendData,
    dataType: "text",
    success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });