[英]Getting not correct data from API Node JS
我希望我没有重复这个问题,但我没有在 stackoverflow 上找到任何问题。
这是一种登录方法,当有人正确登录时,我发送一个带有用户对象的 200 状态代码作为响应,但在客户端我只得到 200 的默认响应,当我使用错误的密码登录时,我得到 500 默认响应没有我发送的任何数据的响应! 当我正确登录时,没有错误消息和对象。
这是中间件
我用
app.use(express.json());
app.use(bodyParser.json());
登录方式
exports.logIn =async (req,res)=>{
let {email,password} = req.body;
let user;
let passwordCorrect;
try{
user = await UserModel.findOne({email:email});
if(user){
console.log("user found")
passwordCorrect= await bcryptjs.compare(password,user.password);
if(passwordCorrect){
console.log("password correct")
res.json({user:user})
}else{
console.log("password not")
throw new Error("password is wrong");
}
}else{
console.log("user not found ")
throw new Error("This user is not in our system");
}
}catch(err){
console.log("catched error ")
console.log(err)
res.status(500).json({
status:'fail',
message:err.message
})
}
}
这是我正确登录时得到的响应,响应缺少从服务器发送的数据,如果密码错误,我收到 500 没有从服务器发送的错误消息
Response {type: "cors", url: "http://localhost:8080/api/user/login", redirected: false, status: 200, ok: true, …}
type: "cors"
url: "http://localhost:8080/api/user/login"
redirected: false
status: 200
ok: true
statusText: "OK"
headers: Headers {}
body: (...)
bodyUsed: false
__proto__: Response
从我使用反应的客户端
try{
const user = await fetch("http://localhost:8080/api/user/login",{
headers:{
"Content-Type":"application/json"
},
method:"POST",
body:JSON.stringify(data)
});
if(user.ok){
// auth.login();
console.log('ok')
console.log(user)
}else{
console.log('not ok')
console.log(user)
setError(user.message)
}
}catch(err){
console.log("error ")
console.log(err);
setError(err)
}
这是接受来自其他域的请求的中间件
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Accses-Control-Allow-Methods","GET,POST,DELETE,PATCH");
console.log(req.body);
next();
});
Javascript fetch api返回一个包含响应的承诺。 这只是一个 HTTP 响应,而不是实际的 JSON。 为了从响应中提取 JSON 正文内容,我们使用json()
方法。
所以你的代码应该是:
try {
const response = await fetch("http://localhost:8080/api/user/login", {
headers: {
"Content-Type": "application/json"
},
method: "POST",
body: JSON.stringify(data)
});
if (response.ok) {
console.log("ok");
let user = await response.json();
console.log("user: ", user);
} else {
console.log("not ok");
console.log(response);
setError(response.message);
}
} catch (err) {
console.log("error ");
console.log(err);
setError(err);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.