簡體   English   中英

我如何獲取我的url請求的Json?

[英]How can i get the Json of my url request?

我想發出一個URL請求,在瀏覽器中嘗試后,其結果將是JSON 我想將整個JSON響應放入var或const中,以便以后進行進一步處理。

到目前為止我嘗試過的是:

app.use(express.bodyParser());

app.post(MY_URL, function(request, response){
    console.log(request.body);
    console.log(request.body;
});

然后 :

app.use(bodyParser.urlencoded({
    extended: true
}));

app.post(MY_URL, function (req, res) {
    console.log(req.body)
});

兩者都還沒有解決,並且成為node.js的初學者沒有幫助。

編輯:為了澄清我的問題:

my_url = https://only_an_example

在瀏覽器中鍵入的URL將在該頁面中提供一個Json,如下所示:

{
  "query": "testing",
  "topScoringIntent": {
    "intent": "Calendar.Add",
    "score": 0.987683
  },
  "intents": [
    {
      "intent": "Calendar.Add",
      "score": 0.987683
    },
    {
      "intent": "None",
      "score": 0.0250480156
    }}

我想要得到的是Json響應並使用node.js打印它。

如果您嘗試獲取請求的正文,請訪問:

req.body;

如果要發送JSON對象作為響應,則可以執行以下操作:

var objectToResponde = {"key1": "value1", "key2": "value"};
res.send(objectToResponde);

在進一步了解了OP的問題(通過以下注釋)之后,您可以將要發送回客戶端的對象轉換為JSON,如下所示:

app.post('some/url', (req, res) => {
    const myObject = {a: 1, b:2};

    res.json(myObject);
});

結果是設置了適當的響應頭的JSON響應。

嘗試這個:

app.use(bodyParser.urlencoded({
   extended: true
}));

app.post(MY_URL, function (req, res) {
    res.status(200).json(<your object>);
});

暫無
暫無

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

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