【问题标题】:Accessing String on Node.js Server from Ajax Post Request从 Ajax 发布请求访问 Node.js 服务器上的字符串
【发布时间】:2018-04-22 14:38:02
【问题描述】:

这是我第一个使用 ajax 和 node.js 的项目,到目前为止,我所有的 POST 请求都是通过表单提交完成的。

我现在尝试使用$.ajax 发送POST 并传递字符串'cocktailid' 以供server.js 在div click() 之后使用。

我想知道最简单的方法是什么。

Ajax 代码

$(".col-sm").click(function(){
  //Append to console a log that cocktail div has been clicked.
  console.log("Cocktail Clicked.");
  console.log(this);

  //Create variable to hold id of cocktail div clicked
  var cocktailid = $(this).attr('id');
  cocktailid = cocktailid.replace(/\s+/g, '_');
  cocktailid = cocktailid.replace(/'/g, '');
  alert(cocktailid);

  $.ajax({
   type: 'POST',
   url: '/adddrink',
   data: { "field1": cocktailid},
   dataType: "json",
   cache: false,
   contentType: "application/json",
   success: function(data) {
    console.log('success');
    console.log(cocktail + 'sent.');
    console.log(JSON.stringify(data));
   }
  });
})
};

服务器.js

app.post('/adddrink', function(req, res){
console.log(req.body);
});

我尝试以几种不同的格式发送数据并遇到不同的问题,目前我的服务器显示以下错误:

SyntaxError: Unexpected token # in JSON at position 0
    at JSON.parse (<anonymous>)
    at createStrictSyntaxError (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/types/json.js:157:10)
    at parse (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/types/json.js:83:15)
    at /home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/body-parser/lib/read.js:121:18
    at invokeCallback (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:224:16)
    at done (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:213:7)
    at IncomingMessage.onEnd (/home/codio/workspace/CocktailMixerGroupRepo/website/node_modules/raw-body/index.js:273:7)
    at IncomingMessage.emit (events.js:160:13)
    at endReadableNT (_stream_readable.js:1101:12)
    at process._tickCallback (internal/process/next_tick.js:152:19)

现在我只想表明我可以访问节点服务器上的字符串。

我已尝试四处寻找解决方案,经过尝试后,我希望我确实过于复杂了我想要实现的目标,我们将不胜感激任何帮助!

【问题讨论】:

    标签: javascript node.js ajax express


    【解决方案1】:

    你必须在data上使用:JSON.stringify

    $.ajax({
      type: 'POST',
      url: '/adddrink',
      data: JSON.stringify({
        "field1": cocktailid
      }),
      dataType: "json",
      cache: false,
      contentType: "application/json",
      success: function(data) {}
    });
    

    没有它,有效负载是 field1=yes 而不是 {"field1":"yes"},这就是为什么您会收到 SyntaxError: Unexpected token # in JSON at position 0,因为您没有发布有效的 JSON。

    对于更详细的错误,您可以在之后添加错误处理中间件body-parser来处理JSON错误。

    app.use(bodyParser.json());
    
    app.use((err, req, res, next) => {
    
        // Body parser middleware Error
        if(err instanceof SyntaxError) {
    
            // err.body contains the actual body that was posted
            // which won't be a valid JSON.
            console.error(`Invalid JSON: ${err.body}`);
    
            return res
                .status(400) // Bad request
                .send({
                    message: 'Invalid JSON'
                });
    
        }
    
        next();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 2012-02-16
      • 1970-01-01
      相关资源
      最近更新 更多