프로젝트/[개인] Auto Packing List Manager

[개인] 카스 전자 저울 연동 Packing List 자동 생성 프로그램 #11 | Node.js에서 req.body의 빈 객체 문제로 인해 body-parser 모듈 적용

DandyNow 2022. 6. 2. 15:01
728x90
반응형

| 이슈

비어있는 req.body

카스 전자저울의 mdb 파일이 있는 경로를 영속적으로 관리하기 위해 mdb 파일이 있는 경로를 mdbpath.txt에 text 형식으로 써두고자 하였다. 그래서-Node.js에서-post 방식으로 req를 받았는데  req.body가 빈 객체로 왔다. 코드와 실행결과는 다음과 같다.

app.post('/mdbpath', (req, res) => {
  console.log(req.body)
  res.send('Ok')
})
PS C:\Users\J\Documents\GitHub\auuto_packing_make\server> node .\papp.js
서버가 포트 3000번으로 시작되었습니다.
{}

 

req.body가 빈 객체로 오는 문제는 body-parser 모듈로 해결이 가능했다.

https://www.npmjs.com/package/body-parser#bodyparsertextoptions

 

body-parser

Node.js body parsing middleware. Latest version: 1.20.0, last published: 2 months ago. Start using body-parser in your project by running `npm i body-parser`. There are 21015 other projects in the npm registry using body-parser.

www.npmjs.com

 

Node.js에 body-parser 모듈을 설치하고 app.js에 다음의 코드를 추가하였다.

import bodyParser from 'body-parser'

app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.text())

 

[그림 1]과 같이 Postman에서 테스트해보니 정상적으로  text 정보가 넘어왔다.

[그림 1] Postman에서 테스트

 

아래는 터미널에 출력된 정상적으로 출력된 내용이다.

PS C:\Users\J\Documents\GitHub\auto_packing_make\server> node .\app.js
서버가 포트 3000번으로 시작되었습니다.
test

 

req.body에 정상적인 값이 넘어오는 것을 확인한 후 다음과 같이 mdbpath.txt 파일에 mdb 파일의 경로 정보를 쓰는 코드를 완성하였다.

app.post('/mdbpath', (req, res) => {
  fs.writeFileSync('./data/mdbpath.txt', req.body, 'utf8', (err) => {
    if (err) {
      throw err
    }
  })
  res.send('Ok')
})

 

| 다음 단계

사용자가 임의로 mdb 데이터가 있는 경로를 수정할 수 있는 기능을 구현하고 있는 중이다. Backend에서 text 형태의 mdb 파일 경로 정보를 영속적으로 기록하는 기능은 구현 및 테스트가 완료되었다. 하지만 Frontend에서 Backend로 경로 정보를 보내는 과정에서 Cors 문제가 발생하였다. 이미 app.js에  Cors를 허용으로 처리하였음에도 불구하고 발생한 에러라 난감한 상황이다.

728x90
반응형