codestates / codestates/conimals
[정새얀] 220607 Error - Handling
- Dominant language
- JavaScript
- Stars
- 3
- Forks
- 5
- PR merge metrics
- No merged PRs in 30d
Description
> 해결된 에러라면 라벨에 'Complete' 를 달아주세요.
> 미해결된 에러라면 라벨을 'In progress' 로 변경해주세요.
### 어떤 에러인가요?
- 카카오 로그인을 하면서 인가 코드와 토큰이 제대로 받아와지지 않고, 데이터베이스에 저장이 되지 않음
(소셜 로그인 기능 자체를 작성했음에도 불구하고 기능 구현이 제대로 되지 않음)
- 로그인 후 마이페이지에 들어갔을 때 userId가 undefined라는 에러가 뜬다.
- as를 잘못 썼다는 에러가 떴다.
- console.log(uploads);를 찍었을 때 Promise { pending }이 나온다.
### 에러 메시지
```bash
Access to XMLHttpRequest at from 'Request URL' origin 'Request Header Origin Url' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
```
```bash
throw new Error(`WHERE parameter "${key}" has invalid "undefined" value`);
^
Error: WHERE parameter "userId" has invalid "undefined" value
```
```bash
throw new sequelizeErrors.EagerLoadingError(`${targetModel.name} is associated to ${this.name} using an alias. You must use the 'as' keyword to specify the alias within your include statement.`);
^
EagerLoadingError [SequelizeEagerLoadingError]: users is associated to posts using an alias. You must use the 'as' keyword to specify the alias within your include statement.
```
```bash
Promise{}
```
### 에러 핸들링 방법
- 첫번째 에러는 클라이언트에서 요청을 보낼 때 redirect uri를 넣어서 보내주어야 하는 줄 알고 넣어 보냈더니 cors에러가 떴다.
이 부분을 환경변수에 저장해둔 REACT_APP_API_URL을 넣어 보내 해결했다.
또한 토큰을 제대로 받지 못하는 부분은 findOrCreate메소드로 변경하여 사용하였더니 해결됐다.
- 두번째 에러는 아예 코드를 바꿔서 작성하여 해결함
```js
// 처음 작성했던 코드
module.exports = async(req, res) => {
const verify = isAuthorized(req);
if (!verify) {
return res.status(400).json({ message: '유효하지 않은 요청입니다' });
} else {
const userInfo = await users.findOne({
attributes: ['id', 'userName', 'userEmail', 'password'],
where: { id: verify.id },
});
const { userName } = req.query;
const uploads = await posts.findAll({
attributes: ['title', 'content', 'image'],
include: [
{
model: users,
},
],
where: { userName },
order: [['createdAt']],
});
if (!userInfo) {
return res.status(401).json({ message: '권한이 없습니다' });
} else {
const { id, userName, userEmail } = userInfo;
return res.status(200).json({
data: {
id,
userName,
userEmail,
},
message: '회원 정보 조회에 성공하였습니다',
});
}
}
}
```
```js
// 수정한 코드
module.exports = async (req, res) => {
const verify = isAuthorized(req);
const { id } = verify;
if (verify) {
await posts
.findAll({
where: { userId: id },
include: [
{
model: users,
required: true,
attributes: ['id', 'userName'],
},
],
attributes: [
'id',
'title',
'content',
'image',
'createdAt',
'updatedAt',
],
order: [['id']],
})
.then((data) => {
const myPosts = data.map((el) => el.get({ plain: true }));
res
.status(200)
.send({ data: myPosts, message: '회원 정보 조회에 성공하였습니다' });
})
.catch((err) => {
console.log(err);
res.status(500).json({ message: '서버가 불러오기에 실패하였습니다' });
});
} else {
res.status(401).send({ message: '유효하지 않은 요청입니다' });
}
};
```
- 세번째 에러는 model에서 관계 설정을 해줄 때 alias(as)를 잘못 설정해준 경우에 나오는 에러 문구였다. as를 굳이 써줄 필요가 없어 지웠더니 해결되었다.
- 네번째 에러는 비동기 함수 처리를 해주지 않았기 때문에 나오는 것으로 await을 붙여주었더니 더이상 나오지 않는다.
### 에러 핸들링을 위해 참고한 레퍼런스 링크
[첫번째 에러](https://data-jj.tistory.com/53)
[세번째 에러](https://velog.io/@kaitlin_k/SequelizeEagerLoadingError-%EA%B4%80%EA%B3%84%EA%B0%80-%EC%9E%88%EB%8A%94-%EB%91%90-%ED%85%8C%EC%9D%B4%EB%B8%94%EC%9D%84-join%ED%95%A0%EB%95%8C-alias-%EC%9E%91%EC%84%B1%EC%98%A4%EB%A5%98-%EC%97%90%EB%9F%AC)
[네번째 에러](https://okky.kr/article/704616)
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.