【问题标题】:Javascript & Node.js - make a JSON requestJavascript 和 Node.js - 发出 JSON 请求
【发布时间】:2015-07-04 11:04:00
【问题描述】:

在这个Question我读到,在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)}})

【问题讨论】:

  • 您是否在 ajax 调用中设置了 datatype = json?
  • 是的,我有,但没有任何区别

标签: javascript jquery json node.js


【解决方案1】:

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

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

但是,Content-Type 标头用于确定 request 正文的格式,而不是响应。建议您使用 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 已经为此提供了一个方便的小method

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

【讨论】:

  • 感谢确实有效,但是当我在浏览器中输入 url(不是 $.ajax)时,它仍然接受 json 格式的请求,这不应该是 html 吗?
  • @user3425760 您可能会发现浏览器告诉服务器它可以接受 JSON 和 HTML 响应。您可以更新您的 get 方法以优先考虑 HTML 而不是 JSON,我已经更新了我的答案来证明这一点。
【解决方案2】:

尝试设置contentType参数

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

编辑:

您可以使用 request Module 你所要做的就是

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 链接。也许那个模块会让你的生活更轻松

【讨论】:

  • 我不需要客户端中的结果,我检查服务器如何查看请求。
  • 首先你必须确保ajax请求被正确发送到服务器
  • 请求发送到服务器很好,因为我可以记录请求。
  • 我没有收到任何错误,请求应该是“json”类型,但它始终是“html”类型,即使是 contentType 和所有内容。
  • 你的答案不是我想要的,但无论如何你都会投票
猜你喜欢
  • 2014-09-30
  • 2015-08-15
  • 2011-08-28
  • 2021-09-04
  • 2018-06-16
  • 2014-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多