【问题标题】:Fetch: Can you pass parameters to the serverFetch:你能把参数传给服务器吗
【发布时间】:2017-10-29 05:59:02
【问题描述】:

我正在使用基本提取从快速服务器获取数据,该服务器从数据库中查询数据。所以我想做一个登录系统,我想通过获取请求从输入字段发送用户/密码。所以我可以执行逻辑检查以查看密码是否与服务器中的数据匹配。并以结果回应。 是否可以做一个可以传递参数的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);
});

【问题讨论】:

    标签: fetch


    【解决方案1】:

    当然可以!

    以下是使用 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
    });
    

    我以前回答过这个问题,请查看此以获取更多详细信息:

    POST Request with 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
    });
    

    【讨论】:

    • 哦,好吧,在服务器端,我只是做一个 app.get 吗?还是 app.post 函数?
    • 基于我的示例,并假设您正在使用 ExpressJS,那么是的 app.post() 是您处理该请求所需要的。
    • 呃,我觉得自己像个白痴,我收到了 post 请求,但我不确定如何提取我传递过来的数据来表达。在 app.post() 函数中。
    • 解析你的数据是一个不同的问题,请遵循本教程并特别注意 JSON 发布请求所需的 body-parser 部分:scotch.io/tutorials/…
    • 我终于得到了它的全部功能,正是 JSON 解析给我带来了一些问题。非常感谢您的耐心和指导!
    猜你喜欢
    • 2021-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-19
    相关资源
    最近更新 更多