요청 바디의 데이터를 읽어 오는 데 자꾸 오류가 나서 애를 먹었다.
Unexpected token " in JSON at position 0
보내온 데이터가 객체나 배열이 아니라 그냥 문자열이라 express.json()
이 파싱을 못하는 것 같은데 어디를 손대야 할지 몰라 한참 헤맸다. 처음에는 요청을 보내는 쪽 코드를 수정해서 문자열이 아니라 키-값으로 된 객체형으로 보내서 해결했다. 그런데 다른 분께서 클라이언트 쪽 코드는 안 건드리고 서버쪽 코드만 수정해서도 할 수 있다고 하셔서 Express.js 공식 문서를 한참 읽었다. 페어 분이랑 한참 침묵속에서 답을 찾다가 둘이 거의 동시에 답을 찾아냈다. express.json()
의 strict
옵션을 false
로 바꾸면 객체나 배열이 아니어도 읽을 수 있게 된다...!
$ npm install express --save
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World');
});
app.listen(port, () => {
console.log(`server listening at http://localhost:${port}`);
});
const cors = require('cors'); // npm install cors로 설치 후 사용
// CASE 1 : 모든 요청에 적용
app.use(cors());
// CASE 2 : 특정 라우트에만 적용
app.get('/', cors(), (req, res) => {
res.send('Hello World');
});
// CASE 3 : CORS 옵션
app.use(cors({
origin: 'http://allowonlythiorigin.com'
}))
// app.METHOD(PATH, HANDLER);
// Example :
app.get('/', (req, res)=> {
res.send('Hello World');
});
app.post('/post', (req, res) => {
// some action to create a new post based on
// the data in the request body
})
app.use(express.json());
// express.json 옵션 설정
// exporess.json({strict: false}) => 배열이나 객체가 외 자료형도 가능 (디폴트 true)
let posts = [];
app.post('/post', (req, res) => {
const newPost = {
createdAt: new Date().toISOString(),
title: req.body.title.toUpperCase(),
author: req.body.author,
content: req.body.content,
id: nanoid()
}
posts.push(newPost);
return res.status(200).json({id: newPost.id})
})
// POST '/post'
// body :
// {
// title: "Hello World",
// author: "Alex J. Lee",
// content: "Welcome to my blog!"
// }
// Using Parameter => req.params
// GET '/posts/someid'
app.get('/posts/:id', (req, res) => {
const data = posts.filter(post => {
return post.id === req.params.id;
})
return res.json(data);
})
// Using Query String => req.query
// GET 'posts/?title={query}'
app.get('/posts', (req, res) => {
if (req.query.title !== undefined) {
const filteredPosts = posts.filter(post => {
return post.title.includes(req.query.title.toUpperCase());
});
return res.status(200).json(filteredPosts);
}
res.json(posts);
})
req
), 응답 객체 (res
), 다음 미들웨어 함수(next
)에 대한 엑세스 권한을 갖는 함수.next
)를 호출한다. 순차적으로 호출되기 때문에 순서가 중요하다. 만약 이어받을 미들웨어가 더 없다면 끝나게 된다.cors
)body-parser
, 또는 express에서 제공하는 parser)// 관리자 권한이 있는지 확인
const checkAdmin = (res, req, next) => {
if (req.headers.Authentification === "admin") {
next();
} else {
res.send("You don't have access");
}
}
app.post('/admin-only', checkAdmin, (res, req) => {
// ...
})