Node.js 교과서 written by 조현영
hy2850 / nodejs_study Goto Github PK
View Code? Open in Web Editor NEWNode.js 교과서 written by 조현영
Node.js 교과서 written by 조현영
API 서버 : http://localhost:8002 에서 호스팅
클라이언트 : http://localhost:4000 에서 호스팅
클라이언트 Front 내부 script에서 8002 서버로 axios request
맨 위 localhost는 클라이언트가 자신의 호스팅 서버4000에 페이지 요청한 것.
아래 axios.min.js는 클라 내부 script에서 CDN에 요청한 것.
token이 Front script에서 8002번 API 서버에 요청한 req
(Chrome default CORS policy) same origin policy (SOP) applies
preflight req : origin differs from host (server)
→ main req : CORS policy violation, req fails
Server allows all sources to access
const cors = require('cors');
router.use(cors());
Access-Control-Allow-Origin
header added
CORS 적용 받고 제대로 받아진 req 모습
Check if client sending request has its domain registered.
Add the domain with cors if it does.
NodeJS_study/Ch 10. 웹 API 서버 만들기/nodebird-api/routes/v2.js
Lines 12 to 30 in 7320e9e
🚨 Protocol (http, https) 까지 완벽히 같아야 같은 Origin - Ref
// req.header('origin') : http://localhost:4000
// host : localhost:4000
cors({ origin: host })(req, res, next); // ❌ Access-Control-Allow-Origin: localhost:4000
cors({ origin: req.header('origin') })(req, res, next); // ✔️ Access-Control-Allow-Origin: http://localhost:4000
Request header Origin: http://localhost:4000
이므로, 완전히 일치하는 후자만 허용
TLDR) Client asks for files that compose the webpage with GET request, but server doesn't serve the requested files with below code. Blank page is shown.
import * as http from 'http';
import * as fs from 'fs/promises';
const users = {}; // 데이터 저장용
const server = http.createServer(async (req, res) => {
try {
if (req.method === 'GET') {
console.log('GET', req.url);
if (req.url === '/') {
const data = await fs.readFile('./restFront.html');
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
return res.end(data);
}
} else if (req.method === 'POST') {
console.log('POST');
} else if (req.method === 'PUT') {
console.log('PUT');
} else if (req.method === 'DELETE') {
console.log('DELETE');
} else {
throw new Error('Unexpected request');
}
} catch (err) {
console.error(err);
}
});
const PORT = 8080;
server.listen(8080);
server.on('listening', () => {
console.log(`Listening on ${PORT}`);
});
server.on('error', (err) => {
console.error(err);
});
Curiosity : When does Passport add 'helper functions' (login()
, logIn()
, logout()
, logOut()
, isAuthenticated()
, and isUnauthenticated()
) to req
object?
// app.js - test middlewares
// For debugging Passport
const checkPassportReq = (req, res, next) => {
console.log('Req object : ', req._passport);
next();
};
console.log('Before initialize');
app.use('/', checkPassportReq);
app.use(passport.initialize()); // 👉🏻 req객체에 passport 설정 삽입
console.log('After initialize, before session');
app.use('/', checkPassportReq);
app.use(passport.session()); // 👉🏻 req.session 객체에 passport 정보 저장
console.log('After session');
app.use('/', checkPassportReq);
Functions are added after passport.session()
Further look-up :
app.use(passport.session());
= app.use(passport.authenticate('session'));
ref
So, passport.authenticate adds those functions to req (ref)
Clicking the name calls getComment
function in public/mongoose.js
, sending GET req to the server
async function getComment(id) {
try {
const res = await axios.get(`/users/${id}/comments`);
...
}
}
Initial requests or any requests after modification to the database (create, update, delete) - response with code 200
Same GET requests afterward - response with code 304
This status code is seemed to be related to 'caching';
Is the browser automatically caching the data or something?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.