Git Product home page Git Product logo

nodejs_study's Introduction

NodeJS_study

Node.js 교과서 written by 조현영

nodejs_study's People

Contributors

hy2850 avatar

Watchers

 avatar

nodejs_study's Issues

[10.7] Understanding CORS

API 서버 : http://localhost:8002 에서 호스팅
클라이언트 : http://localhost:4000 에서 호스팅

클라이언트 Front 내부 script에서 8002 서버로 axios request

axios.post('http://localhost:8002/v2/token', {


Network 탭

맨 위 localhost는 클라이언트가 자신의 호스팅 서버4000에 페이지 요청한 것.
아래 axios.min.js는 클라 내부 script에서 CDN에 요청한 것.
token이 Front script에서 8002번 API 서버에 요청한 req

image


Request/Response headers per situation

1. No CORS setting

(Chrome default CORS policy) same origin policy (SOP) applies

preflight req : origin differs from host (server)

image

→ main req : CORS policy violation, req fails

image


2. CORS - allow all

Server allows all sources to access

const cors = require('cors');
router.use(cors());

Access-Control-Allow-Origin header added

image

CORS 적용 받고 제대로 받아진 req 모습

image


3. CORS - allow specific domains registered on DB

Check if client sending request has its domain registered.
Add the domain with cors if it does.

// router.use(cors()); // 10-7
// Check if the client domain is registered and allow it with cors
router.use(async (req, res, next) => {
// req.header('origin') : http://localhost:4000
// host : localhost:4000
const { host } = new URL(req.header('origin'));
const domain = await Domain.findOne({
where: { host },
});
if (domain) {
// router.use(cors({ origin: host })); // ❌ Embedding middleware inside middleware - use below code
// cors({ origin: host })(req, res, next); // 🔥 req denied; mismatching origin
cors({ origin: req.header('origin') })(req, res, next);
} else {
next();
}
});


🚨 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 이므로, 완전히 일치하는 후자만 허용

image

[4.3] Serving requested files on GET request

Problem 1

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.

image

Code

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);
});

[9.3] Passport passport.initialize, passport.session middleware 탐구

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)

[8.6] Multiple same GET requests cached automatically? (HTTP 302 response)

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`);
    ...
  }
}

image

Initial requests or any requests after modification to the database (create, update, delete) - response with code 200

image

Same GET requests afterward - response with code 304

image

This status code is seemed to be related to 'caching';
Is the browser automatically caching the data or something?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.