【问题标题】:Undefined variable while passing data from ajax to node js将数据从ajax传递到节点js时未定义的变量
【发布时间】:2017-02-26 00:03:14
【问题描述】:

我正在尝试将数量从 ajax 传递到节点 js,但我得到的只是节点服务器中的未定义。这是ajax代码。

self.information = function() {
    var x = {"amount" : self.amount()};
    var string = JSON.stringify(x);
    console.log(string);
      $.ajax({
          type: 'GET',
          url: 'http://localhost:3000/getIOT',
          contentType: 'application/json; charset=utf-8',
          dataType: 'json',
          data: string
      })
      .done(function(result) {
       console.log(result);
      })
      .fail(function(xhr, status, error) {
          console.log(error);
      })
      .always(function(data){
      });
  }
}

The console.log(string) shows {"amount" : "1000"} 在我看来是正确的。现在在节点 js 服务器中,我试图查看变量名,但它显示未定义。

const path = require('path');
const http = require('http');
const express = require('express');
const cors = require('cors');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var requestify = require('requestify');
var request = require('request');
var helmet = require('helmet');
var https = require('https');

var app = express();
app.use(helmet());

const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(express.static(publicPath));


app.get('/getIOT', function (req, res , err) {
            console.log('body: ' + JSON.stringify(req.body));
             // SHOWS {}  above
            var amount = req.body.amount;
            console.log(req.body.amount);
            // SHOWS UNDEFINED ABOVE 
});



app.listen(port, () => {
  console.log(`Server is up on ${port}`);
});

金额使用淘汰赛js,因此self.amount()

【问题讨论】:

    标签: javascript node.js ajax query-string


    【解决方案1】:

    如果您想使用 get,只需将内容类型更改为 application/x-www-form-urlencoded 并将数据作为查询字符串发送并作为 json 对象发送

    如果你想发帖:

     amount=12&otherprop=xxx
    

    改成

     var x = {"amount" : self.amount()};
     $.ajax({
          type: 'GET',
          url: 'http://localhost:3000/getIOT',
          contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
          dataType: 'json',
          data: x
      });
    

    在 nodejs 中

    使用 req.query 取回数据

    app.get('/getIOT', function (req, res , err) {
                console.log('body: ' + req.query);
                 // SHOWS {}  above
                var amount = req.query.amount;
                console.log(req.query.amount);
                // SHOWS UNDEFINED ABOVE 
    });
    

    【讨论】:

    • 您的回答对我很有帮助,但我想问一下,POST 对我不起作用,您能告诉我为什么会导致我出错吗?
    • 我得到一个错误。 SyntaxError: Unexpected token a at parse (/Users/nihit/Documents/node/multiple-js/node_modules/body-p‌​arser/lib/types/json‌​.js:83:15) at /Users/nihit/Documents/ node/multiple-js/node_modules/body-pa‌​rser/lib/read.js:116‌​:18 在 invokeCallback (/Users/nihit/Documents/node/multiple-js/node_modules/raw-bo‌​dy/index. js:262:16) 完成 (/Users/nihit/Documents/node/multiple-js/node_modules/raw-bo‌​dy/index.js:251:7)
    • 哦.. 只​​需解析 json 字符串而不是 stringify。将 JSON.stringify(req.body) 更改为 JSON.parse(req.body);
    • 您正在向 nodejs 发送 json 字符串,为什么您必须再次对其进行字符串化。如果您想使用 post,只需解析该 json 字符串即可。
    • 同时删除 bodyParser.urlencoded({extended:false})。这告诉浏览器发送 url 形式的编码数据而不是 json。
    【解决方案2】:

    如果您使用 HTTP GET 请求,我相信 jQuery 的 .ajax 在查询参数中发送数据。我会检查req.query 而不是req.body,或者将ajax 调用更改为type: 'POST' 以在req.body 中获取它。

    如果这听起来像一堆废话,我可以尝试更详细地解释:)

    【讨论】:

    • 由于OP在Request中将contentType设置为contentType: 'application/json',所以应该会在req.body接收到
    • 你确定吗?来自数据属性的 jQuery 文档:Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
    • @thataustin POST 发出错误请求 :(
    • 我认为通过POST 请求,您不需要对其进行字符串化。只需传入一个 JS 对象:data: x。另外,请记住告诉服务器您正在等待将app.get 更改为app.post 的帖子。但老实说,我认为使用查询参数更好。 req.query 工作了吗?
    • @thataustin,你在正确的轨道上(而我不是)。 GET 请求不填充 req.body,但 POST 请求填充。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-23
    • 1970-01-01
    相关资源
    最近更新 更多