我正在使用POST方法和两个参数来访问login.php。作为响应,它将返回状态和消息参数,但我没有从login.php获得响应。我要管理此消息“用户名或密码错误。” 。如果我控制台“响应”,它将返回以下内容:
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(), … }
我的代码是:
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);
});
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);
答案 0 :(得分:0)
似乎您得到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()