我如何获得我的网址请求的Json?

时间:2017-12-14 11:23:19

标签: javascript json node.js

我想发一个网址请求,在浏览器中尝试后,结果会是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打印它。

3 个答案:

答案 0 :(得分:0)

如果您尝试获取请求的正文,只需访问:

req.body;

如果要将JSON对象作为响应发送,可以执行以下操作:

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

答案 1 :(得分:0)

在进一步了解OP的问题后(​​通过下面的评论),您可以将要发送回客户端的对象转换为JSON,如下所示:

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

    res.json(myObject);
});

结果是JSON响应,并设置了相应的响应标头。

答案 2 :(得分:0)

试试这个:

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

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