如何将ajax get请求数据传递给nodejs的GET路由?

5

这是我的ajax请求调用

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

这是在Node.js中的GET路由。
app.get('/refresh', function(req, res) {
            console.log("My data" + JSON.stringify(req.body));
            //other operations
        }

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


你是否遇到任何错误? - Deepansh Sachdeva
1
您正在进行GET请求,没有请求正文来描述内容类型。声称请求的内容类型为JSON是错误的。 - Quentin
2个回答

5

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
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接