gpt4 book ai didi

fetch:能不能把参数传给服务器

转载 作者:行者123 更新时间:2023-12-03 15:29:45 25 4
gpt4 key购买 nike

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

更新代码如下:

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

express 功能
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
});

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

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

关于fetch:能不能把参数传给服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44233791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com