http 모듈
const http = require('http');
const PORT = 5000;
const ip = 'localhost';
const server = http.createServer((request, response) => {
if (request.method === 'OPTIONS') {
response.writeHead(200, defaultCorsHeader);
response.end();
} else if (request.method === 'POST' && request.url === '/upper') {
response.writeHead(200, defaultCorsHeader);
let body = [];
request
.on('data', (chunk) => {
body.push(chunk);
})
.on('end', () => {
body = Buffer.concat(body).toString().toUpperCase();
response.write(body);
response.end();
})
.on('error', console.error);
} else if (request.method === 'POST' && request.url === '/lower') {
response.writeHead(200, defaultCorsHeader);
let body = [];
request
.on('data', (chunk) => {
body.push(chunk);
})
.on('end', () => {
body = Buffer.concat(body).toString().toLowerCase();
response.end(body);
})
.on('error', console.error);
} else {
console.log(
`http request method is ${request.method}, url is ${request.url}`
);
response.writeHead(400, defaultCorsHeader);
response.end('hello mini-server sprints');
}
});
server.listen(PORT, ip, () => {
console.log(`http server listen on ${ip}:${PORT}`);
});
const defaultCorsHeader = {
'Access-Control-Allow-Origin': 'http://127.0.0.1:4000',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Accept',
'Access-Control-Max-Age': 10,
};
express로 리팩토링
const express = require('express');
const PORT = 5000;
const ip = 'localhost';
const app = express();
const cors = require('cors');
const defaultCorsHeader = {
origin: '*',
methods: 'GET, POST, PUT, DELETE, OPTIONS',
allowedHeaders: 'Content-Type, Accept',
maxAge: 3,
};
app.use(cors(defaultCorsHeader));
app.use(express.json({ strict: false }));
// app.options('/*', cors(defaultCorsHeader));
app.get('/upper', (req, res, next) => {
res.status(200).json('upper get ok');
});
app.post('/upper', (req, res, next) => {
res.status(200).json(req.body.toUpperCase());
});
app.post('/lower', (req, res, next) => {
res.status(200).json(req.body.toLowerCase());
});
app.use((error, req, res, next) => {
res.status(404).send('system error');
});
app.listen(PORT, ip, () => {
console.log(`http server listen on ${ip}:${PORT}`);
});
CORS 정리 내용