获取:您可以将参数传递到服务器吗?

Eri*_*ric 0 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));
Run Code Online (Sandbox Code Playgroud)

快速功能

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

hel*_*bus 5

当然可以!

这是使用POST请求进行抓取的示例:

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
});
Run Code Online (Sandbox Code Playgroud)

我之前已经回答了这个问题,请查看以下详细信息:

使用Fetch API发布请求?

要在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
});
Run Code Online (Sandbox Code Playgroud)

  • 我终于得到了它的全部功能,是 JSON 解析给我带来了一些问题。非常感谢您的耐心和指导! (2认同)