繁体   English   中英

Javascript和Node.js-发出JSON请求

[英]Javascript & Node.js - make a JSON request

在这个问题中,我读到在node.js中可以区分html请求和json请求,如下所示:

app.get('/route', function (req, res) {
    if (req.is('json')) res.json(data);
    else if (req.is('html')) res.render('view', {});
    else ...
});

现在我的问题是如何在节点服务器中发出被解释为json的请求?
因为我尝试使用$ .ajax和$ .getJson并在浏览器中键入所有内容,都是html请求。
这是我的要求

$.ajax({ type: 'GET', url: "/test", dataType:"json", success: function(data){log(data)}})

req.is方法通过检查Content-Type标头检查传入的请求类型,因此您需要确保在发送之前在请求中设置了此标头,例如

$.ajax({
    type: 'GET',
    url: '/route',
    contentType: "application/json; charset=utf-8",
    ....
});

但是, Content-Type标头用于确定请求正文的格式,而不是响应的格式。 建议您改用Accept标头来通知服务器哪种格式适合响应,例如

app.get('/route', function (req, res) {
    if (req.accepts('html')) {
        res.render('view', {});
    } else if (req.accepts('json')) {
        res.json(data);
    } else {
        ...
    }
});

然后,在客户端上,您无需担心Content-header ,而只需担心Accept报头,而jQuery已经为此提供了一个方便的小方法

$.getJSON('/route', function(data) {
    ...
});

尝试设置contentType参数

$.ajax({
    type: 'GET',
    url: 'your_url',
    data: {
        test: "test"
    },
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    ....
});

编辑:

您可以使用请求模块,您所要做的就是

var request = require('request');

var options = {
  uri: 'your_server_side_url',
  method: 'POST',
  json: {
    "data": "some_data"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});

查看该github链接。 可能那个模块会让您的生活更轻松

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM