繁体   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