【问题标题】:How to pass the ajax get request data to nodejs GET route? [duplicate]如何将ajax get请求数据传递给nodejs GET路由? [复制]
【发布时间】:2018-02-19 07:18:05
【问题描述】:

这是我的 ajax 请求调用

  $.ajax({
    url: '/refresh',
    type: 'GET',
    contentType: "application/json",
    data: {
        Name: $("#inputName").val(),
        Url: $("#inputUrl").val()
    },
    success: function(data) {
        console.log('form submitted.' + data);
    }
  });

这是nodejs中的GET路由

app.get('/refresh', function(req, res) {
            console.log("My data" + JSON.stringify(req.body));
            //other operations
        }

如何在我的 js 中获取从 ajax 调用传递的数据?请帮忙!!非常感谢!

【问题讨论】:

  • 你有什么错误吗?
  • 您正在发出 GET 请求,没有请求正文来描述其内容类型。声称请求的内容类型是 JSON 是错误的。

标签: javascript node.js ajax express


【解决方案1】:

jQuery 的 .ajax() 方法将 data 属性作为 GET 请求的查询字符串发送,因此在您的 Express 代码中,您必须从 req.query 而不是从 req.body 检索该数据。

【讨论】:

    【解决方案2】:

    您可以简单地使用req.query

    const id = req.query._some_query_param; // $_GET["id"]
    
    // Sample URL: https://foo.bar/items?id=234
    app.get("/items",function(req,res){
       const id = req.query.id;
       //further operations to perform
    });
    

    如果你想获取路由参数,你可以使用req.params,它只获取路由参数而不是查询字符串参数。

    例如:

    // Sample URL: https://foo.bar/items/322
    app.get("items/:id",function(req,res){
     const id = req.params.id;
     //further operations to perform
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 2020-05-25
      • 2015-08-27
      • 2020-02-25
      相关资源
      最近更新 更多