【问题标题】:How to read the data from node js post ajax request?如何从节点 js 发布 ajax 请求中读取数据?
【发布时间】:2017-10-13 07:37:32
【问题描述】:

我正在尝试将数据从客户端发送到服务器(节点 js)。我正在使用 ajax。

客户:

$("#test_button").on("click",function(){
    //alert("shit");
    $.ajax(
        {url: "http://localhost:4000/ajax_check", 
        async: false, 
        type: "POST",
        data: "{user:balayya,password:hero}",
        success: function(result){
            alert("hooli");
        }});
});

服务器:

var app = require('express')();
var express = require('express');
var http = require('http').Server(app);


http.listen(process.env.PORT || 4000, function() {
    console.log('listening on *:4000');
});

app.use(express.static('publuc'));

app.get('/', function(req, res) {
    console.log("new entry page serving");
    res.sendFile(__dirname + '/main.html');
});

app.post('/ajax_check', function(req, res){
    console.log("someone came in here");
    console.log(req.query.data);
});

console.log() 打印为 "undefined" 。 在节点 js 中接收发布请求及其来自客户端的数据的正确方法是什么

【问题讨论】:

  • 添加一个body-parser这个工作。
  • 如果这是您的解决方案,您应该单击答案下方的复选标记。它将帮助将来偶然发现此问题的其他人。

标签: javascript jquery node.js ajax web


【解决方案1】:

使用这个 npm 包 - https://www.npmjs.com/package/body-parser

因此服务器站点解析如下: request.body.{一些字段名}

【讨论】:

    【解决方案2】:

    试试这样:

    $.ajax({
        url: "http://localhost:4000/ajax_check", 
        type: "POST",
        data: {
            user: "balayya",
            password: "hero"
        },
        success: function(result) {
            alert("hooli");
        }
    });
    

    并在服务端使用req.body.param_name读取对应的参数值:

    app.post('/ajax_check', function(req, res){
        console.log("someone came in here");
        console.log(req.body.user);
        console.log(req.body.password);
    });
    

    还请注意,我已从您的 AJAX 请求中删除了 async: false,因为每次有人将此属性设置为 false 时,一只可怜的小猫就会死去。

    【讨论】:

    • 为此工作添加一个正文解析器。谢谢 。我保证不会杀死一只可怜的小猫。
    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多