我正在尝试通过使用api调用创建一个简单的登录页面来学习反应本机应用程序.我将把用户名和密码发送到api,它会给我回复.但我不能这样做.好吧,我在这里分享我的代码......
var myRequest = new Request('<my API >', {method: 'POST', body: '{"username":this.state.uName , "password":this.state.pwd}'});
fetch(myRequest).then(function(response) {
alert('Res'+response);
}).then(function(response) {
alert('Blank'+response);
})
.catch(function(error) {
alert('Error'+error);
});
Run Code Online (Sandbox Code Playgroud)
我认为将我的用户名和密码传递给服务器的方式是错误的.请给我一些想法然后我可以理解这里有什么问题.
小智 13
var data = {
"username": this.state.username,
"password": this.state.password
}
fetch("https://....", {
method: "POST",
headers: headers,
body: JSON.stringify(data)
})
.then(function(response){
return response.json();
})
.then(function(data){
console.log(data)
});
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助.
您需要将 json 数据字符串化以将请求作为带有 Json 参数的 Post 方法发送,因为您正在尝试执行此操作...这是有关如何在请求响应之前对数据进行编码的示例代码
fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
})
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18289 次 |
| 最近记录: |