簡體   English   中英

從Ajax發布請求訪問Node.js服務器上的字符串

[英]Accessing String on Node.js Server from Ajax Post Request

這是我的第一個使用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));
   }
  });
})
};

Server.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)

現在,我只想顯示我可以訪問節點服務器上的字符串。

我一直在嘗試尋找解決方案,在嘗試之后,我希望我真的對要實現的目標過於復雜,對您的幫助將不勝感激!

您必須使用: JSON.stringify data

$.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獲取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();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM