express / axios

2025. 5. 13. 14:41Coding Study/Node.js

express

 

pakage.json 파일에서 type 을 module 로 작성해야 import 문법으로 가져 올 수 있다.

작성하지 않으면 require 로 가져오면 된다.

  "author": "",
  "license": "ISC",
  "type": "module",   // 모듈로 작성해야 import 문법 사용 가능 하다.
  "bugs": {
    "url": "https://github.com/OZ-Coding-School/nodejs-express-axios-cors/issues"
  },

 

 

express 초기 설정

import express from "express";
import cors from "cors";

const app = express();           // app을 express 로 사용

app.use(express.json());         // json 을 기본적으로 변환 해온다.
app.use(express.text());         // text 를 기본적으로 변환 해온다.

app.use(
  cors({
    origin: "http://127.0.0.1:5501",
    method: ["OPTIONS", "POST", "GET", "PUT", "DELETE"],
    allowedHeaders: ["Content-Type"],
  })
);

 

 

app.use(express.json());  설정 시

만약에 클라이언트에서 객체를 아래와 같이 json 파일로 보내면

const axios = require('axios');

// JSON 형식으로 요청 보내기
axios.post('http://localhost:3000/json', {
  name: 'Alice',
  age: 30
}, {
  headers: {
    'Content-Type': 'application/json'
  }
});

 

 

이런식으로 파싱되어서 서버로 전달된다.

{ "name": "Alice", "age": 30 }

 

 

 

서버에서는 req.body 에 객체로 바로 전달받을 수 잇다.

app.post('/json', (req, res) => {
  console.log('JSON 요청 수신');
  console.log('req.body:', req.body);
  res.send('JSON received');
});

 

{ name: 'Alice', age: 30 } //req.body 출력값

 

 

 

 

app.use(express.text()); 설정 시

 

문자열로 전달 

// TEXT 형식으로 요청 보내기
axios.post('http://localhost:3000/text', 'Hello, world!', {
  headers: {
    'Content-Type': 'text/plain'
  }
});
"Hello, world!"

 

 

서버에서는 문자열로 바로 받아 온다.

app.post('/text', (req, res) => {
  console.log('TEXT 요청 수신');
  console.log('req.body:', req.body);
  res.send('Text received');
});

 

	"Hello, world!" // req.body 출력값

 

 

 

axios

기존 fetch 메소드 를 axios 에서는 좀더 간결하게 작성이 가능 하다.

그리고 then 체인을 1번만 사용 해서 text 나 json 을 자동으로 변환 해준다.

fetch("http://localhost:3000", {
    method: "POST",
    body: newTodo,
  })
    .then((res) => res.text())
    .then((res) => console.log(res));

 

 

 

 

axios는 기본적으로 2번째 인자를 값으로 전달할 때 객체형태로 전달해야 한다.

 

axios.post("http://localhost:3000", { newTodo }) // { newTodo : newTodo} 키와 값이 동일
    .then((res) => console.log(res))

 

 

문자열로 보내고 싶을 때 header axios 의 세번째 인자로 헤더를 아래와 같이 작성한다.

axios.post("http://localhost:3000", newTodo, {
      headers: { "Content-type": "text/plain" },
    })
    .then((res) => console.log(res))

 

 

 

delete 메소드는 전달할 인자를 키값으로 data 로 작성을 해주어야 

서버에서 req.body 값으로 전달이 된다.

const deleteTodo = (id) => {
  return axios
    .delete("http://localhost:3000", { data: id })
    .then((res) => console.log(res.data));
};

'Coding Study > Node.js' 카테고리의 다른 글

카카오 로그인 기능 구현  (0) 2025.05.16
OAuth 인증  (0) 2025.05.16
token 인증방식  (0) 2025.05.15
Session  (0) 2025.05.14
cookie  (0) 2025.05.14