如何在reactjs中从api url usinf fetch获取响应数据
我正在使用POST方法和两个参数访问login.php。作为响应,它将返回一个状态和消息参数,但我没有从login.php得到响应。我想控制台此消息“用户名或密码错误”。如果我控制台“response”,它将返回以下内容:如何在reactjs中从api url usinf fetch获取响应数据,reactjs,Reactjs,我正在使用POST方法和两个参数访问login.php。作为响应,它将返回一个状态和消息参数,但我没有从login.php得到响应。我想控制台此消息“用户名或密码错误”。如果我控制台“response”,它将返回以下内容: body: ReadableStream { locked: false ...} bodyUsed: false headers: Headers { <prototype>... } ok: true redirected: false status: 200
body: ReadableStream { locked: false ...}
bodyUsed: false
headers: Headers { <prototype>... }
ok: true
redirected: false
status: 200
statusText: "OK"
type: "basic"
url: "http://localhost/reactjs/example1/code/login.php"
<prototype>: ResponsePrototype { clone: clone(), arrayBuffer: arrayBuffer(), blob: blob(), … }
body:ReadableStream{locked:false…}
bodyUsed:假
标题:标题{…}
好的,没错
重定向:错误
现状:200
状态文本:“确定”
类型:“基本”
url:“http://localhost/reactjs/example1/code/login.php"
:ResponsePrototype{clone:clone(),arrayBuffer:arrayBuffer(),blob:blob(),…}
我的代码是:
const payload = {
username: this.state.email,
password: this.state.password
}
fetch(`/reactjs/example1/code/login.php`, {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(response => {
if (response.status >= 200 && response.status < 300) {
console.log(response);
}
}).catch(error => {
console.log(error);
});
const有效载荷={
用户名:this.state.email,
密码:this.state.password
}
fetch(`/reactjs/example1/code/login.php`{
方法:“POST”,
正文:JSON.stringify(有效负载),
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”,
},
})。然后(响应=>{
如果(response.status>=200&&response.status<300){
控制台日志(响应);
}
}).catch(错误=>{
console.log(错误);
});
login.php:
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json);
if(isset($obj->username) && !empty($obj->username) && isset($obj->password) && !empty($obj->password) ){
if($obj->username == 'spatel@bamko.net' && $obj->password == '123456'){
$result = array('status'=> 1, 'username'=> 'spatel@bamko.net' );
}else{
$result = array('status'=> 0, 'message'=> 'Username or Password is wrong.' );
}
}else{
$result = array('status'=> 0, 'message'=> 'Username or Password is blank.' );
}
echo json_encode($result);
您似乎得到了arrayBuffer
的响应
您可以尝试以下代码:-
fetch(`/reactjs/example1/code/login.php`, {
method: 'POST',
body: JSON.stringify(payload),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then(res => res.arrayBuffer())
.then(function(buffer) {
console.log(buffer)
});
如果您想要json
输出,我们通常会这样做
res => res.json()
React代码在哪里?没有使用您的响应主体。在您的案例-response中,我更改了变量名。