Fetch:能不能给服务器传参数

Fetch: Can you pass parameters to the server

我正在使用基本提取从从数据库查询数据的快速服务器获取数据。所以我想做一个登录系统,我想用获取请求从输入字段发送 user/password 。所以我可以执行逻辑检查以查看密码是否与服务器中的数据匹配。并回应结果。 是否可以做一个可以传递参数的fetch?

更新了下面的代码:

let fetchData = {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  body: JSON.stringify({
    username: this.state.user,
    password: this.state.password
  })
}

var fromServer = fetch('http://localhost:3000/', fetchData)
.then(function(response){
  if( !response.ok){
    throw Error (response.statusText);
  }
  return response.json();
})
.then(function(response) {
  console.log(response);
})
.catch(error => console.log("there was an error --> " + error));

表达函数

app.post('/', function(req, res){
  var uname = req.body.username;
  var pw = req.body.password;
  console.log(uname);
  console.log(pw);
});

当然可以!

这是使用 POST 请求的 Fetch 示例:

fetch("http://example.com/api/endpoint/", {
  method: "post",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },

  //make sure to serialize your JSON body
  body: JSON.stringify({
    name: myName,
    password: myPassword
  })
})
.then( (response) => { 
   //do something awesome that makes the world a better place
});

我之前已经回答过这个问题,查看这里了解更多详情:

要在 Express 中处理请求,如评论中所述,假设您的 Express 服务器设置为解析正文请求,您可以这样做:

app.post('/your/route', function(req, res) {
    var name= req.body.name;
    var password = req.body.password;

    // ...do your bidding with this data
});