Programming/JavaScript
NodeJS rest-client API JSON이 undefined로 나올때
2mukee
2022. 7. 30. 15:42
320x100
320x100
개요
: VSCode의 rest-client를 통한 API 테스트 중 JSON 형식을 맞추고 request를 보냈음에도
nodeJS 서버에서는 req.body를 undefined로 받는 현상
원인
: json 데이터를 읽기 위해서는 따로 파싱을 해줘야 하는데 파싱하는 과정 없이 json 데이터를 읽으려 했기 때문
해결방법
- body-parser 패키지 설치
: npm install body-parser
- index.js 혹은 app.js 와 같이 라우터를 정의하는 곳에 다음과 같은 코드를 추가
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
Refference
request.body.file getting undefined in node js rest api Code Example
var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json())
www.codegrepper.com
300x250
728x90