이 질문을 반복하지 않았기를 바라지 만 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();
});
자바 스크립트 가져 오기 API 는 응답이 포함 된 약속을 반환합니다. 이것은 실제 JSON이 아닌 HTTP 응답입니다. 응답에서 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);
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다