【问题标题】:Jquery ajax to Express not able to catch data json datajQuery ajax to Express 无法捕获数据 json 数据
【发布时间】:2017-01-23 03:12:32
【问题描述】:

当我向快递发送 Ajax 请求时,我使用 req.body.email 捕获 json 数据 控制台中的输出给我 undefined....请帮助...

客户端

$.ajax({
          url: '/getRandomPass',
          dataType: "json",

          data:{'emailId':'sampleemailiD@gmail.com'},
          type: 'POST',
          cache: false,
          success: function(data) {
            console.log("cleint recieved data",data);
           // this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
           console.log(xhr,status,err);
          }.bind(this)
    })

服务器端

    app.use(bodyParser.json());
   app.post('/getRandomPass', function(req, res) {
       console.log("req",req.body.emailId);
        });

【问题讨论】:

  • 您是否设置了响应内容类型?
  • 你的意思是console.log("on success",data);打印html内容吗?
  • @DustinToothless:我确实将内容类型设置为文本,例如 res.set('Content-Type','text')

标签: jquery node.js express body-parser


【解决方案1】:

使用 $.getJSON 来使用 Json 结构。检查链接 http://api.jquery.com/jquery.getjson/

$.getJSON("/getRandomPass", function( data ) {
        console.log("on success",data);
       });

【讨论】:

  • 仍然获取 html
【解决方案2】:

您应该使用:

res.set('Content-Type', 'text/plain');
res.send(text)

或:

res.end(text)

【讨论】:

  • 我已经分别使用了这两种方法来测试这些东西,但都没有效果
  • 那你的代码的另一部分肯定有其他问题。
  • 请您使用 TeamViewer 或 Skype 并循环查看我的代码
猜你喜欢
  • 1970-01-01
  • 2017-12-25
  • 2012-01-19
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多