Express.js req.body가 정의되지 않았습니다.
이것을 Express 서버의 구성으로 가지고 있습니다.
app.use(app.router);
app.use(express.cookieParser());
app.use(express.session({ secret: "keyboard cat" }));
app.set('view engine', 'ejs');
app.set("view options", { layout: true });
//Handles post requests
app.use(express.bodyParser());
//Handles put requests
app.use(express.methodOverride());
하지만 여전히 내가 요청할 때req.body.something내 경로에서 나는 그것을 지적하는 약간의 오류를 지적합니다.body is undefined은 다은다사경예로입다니의는용을 의 예입니다.req.body:
app.post('/admin', function(req, res){
console.log(req.body.name);
});
나는 이 문제가 다음의 부족으로 인해 발생한다고 읽었습니다.app.use(express.bodyParser());보다시피 경로 앞에 있는 것입니다.
단서는?
2020년 7월 업데이트
express.bodyParser()더 이상 익스프레스의 일부로 번들되지 않습니다.로드하기 전에 별도로 설치해야 합니다.
npm i body-parser
// then in your app
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
})
// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
// create user in req.body
})
자세한 내용은 여기를 참조하십시오.
최초의 추종
경로를 정의하기 전에 모든 구성을 정의해야 합니다.해서 이게하다계수사있다습니용할속음을을 사용할 수 .express.bodyParser().
예는 다음과 같습니다.
var express = require('express'),
app = express(),
port = parseInt(process.env.PORT, 10) || 8080;
app.configure(function(){
app.use(express.bodyParser());
});
app.listen(port);
app.post("/someRoute", function(req, res) {
console.log(req.body);
res.send({ status: 'SUCCESS' });
});
Express(4.x)의 최신 버전은 핵심 프레임워크에서 미들웨어를 분리했습니다.바디 파서가 필요한 경우 별도로 설치해야 합니다.
npm install body-parser --save
그리고 나서 당신의 코드로 이것을 하라.
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())
익스프레스 4, 바디 파서가 내장되어 있습니다.별도의 바디 파서를 설치할 필요가 없습니다.다음과 같이 작동합니다.
export const app = express();
app.use(express.json());
니요를 . 당신은 사용해야 합니다.app.use(express.bodyParser()) 앞에app.use(app.router). . . . . . . . . . . .app.use(app.router)당신이 마지막으로 부르는 것이어야 합니다.
요청 헤더의 내용 유형은 특히 컬 또는 다른 도구에서 데이터를 게시할 때 매우 중요합니다.
application/x-www-form-urlenced, application/json 등을 사용하고 있는지 확인하십시오. 게시물 데이터에 따라 다릅니다.이 필드를 비워 두면 Express가 혼동됩니다.
먼저 다음을 호출하여 'body-parser'라는 이름의 npm 모듈을 설치했는지 확인합니다.
npm install body-parser --save
그런 다음 경로를 호출하기 전에 다음 행을 포함했는지 확인합니다.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
이미 한 댓글에 올린 것처럼, 저는 그것을 사용하여 해결했습니다.
app.use(require('connect').bodyParser());
대신에
app.use(express.bodyParser());
왜 모르겠어요.express.bodyParser()작동하지 않습니다...
당신의 하세요.app.js
라우터가 호출하기 전에
const app = express();
app.use(express.json());
질문에 답했습니다. 꽤 이고 하만꽤일기때이문에적반지▁it▁since때▁but문에▁generic▁is▁quite▁and기이.req.body정의되지 않은 것은 빈번한 오류입니다. 특히 초보자에게는 여기가 문제에 대해 알고 있는 모든 것을 다시 시작하기에 가장 좋은 장소입니다.
이 오류는 다음과 같은 이유로 발생할 수 있습니다.
[SERVER 측] [꽤 자주] 파서 미들웨어를 잊어버리거나 잘못 사용함
- 수신 요청을 구문 분석하려면 적절한 미들웨어를 사용해야 합니다.를 들면, 들면를예,
express.json()형식으로 하고 JSON 파일을 저장합니다.express.urlencoded()요청을 URL 인코딩 형식으로 구문 분석합니다.
const app = express();
app.use(express.urlencoded())
app.use(express.json())
Express(XML, 폼 데이터...)에서 요청에 적합한 구문 분석기를 찾을 수 없는 경우에는 해당 구문 분석을 위한 다른 라이브러리를 찾아야 합니다.예를 들어 XML 데이터를 구문 분석하려면 이 라이브러리를 사용할 수 있습니다.
경로 선언 부분 전에 파서 미들웨어를 사용해야 합니다(이것을 확인하기 위해 테스트를 했습니다!).미들웨어는 초기화 익스프레스 앱 직후에 구성할 수 있습니다.
지적된 다른 답변과 마찬가지로, bodyParser는 express 4.16.0 이후에 더 이상 사용되지 않습니다. 위와 같이 기본 제공 미들웨어를 사용해야 합니다.
[CLIENT 쪽] [희귀] 요청사항과 함께 데이터를 보내는 것을 잊었습니다.
- 자료를 보내주셔야 합니다
데이터가 요청과 함께 전송되었는지 확인하려면 브라우저의 devtools에서 네트워크 탭을 열고 요청을 검색합니다.
- 드물지만 GET 요청에 대한 GET 요청에서 데이터를 보내려는 사람을 보았습니다.
req.body정의되지 않았습니다.
[서버 & 클라이언트] [꽤 자주] 다른 컨텐츠 유형 사용
서버와 클라이언트는 서로를 이해하기 위해 동일한 내용 유형을 사용해야 합니다.다음을 사용하여 요청을 보내는 경우
json사해, 용야합니다를 해야 합니다.json()미들웨어다음을 사용하여 요청을 보내는 경우urlencoded사해, 용야합니다를 해야 합니다.urlencoded()...당신이 파일을 업로드하려고 할 때 하나의 까다로운 경우가 있습니다.
form-data서식을 정하다이를 위해 멀티파트/폼 데이터를 처리하기 위한 미들웨어인 더덕더를 사용할 수 있습니다.만약 당신이 고객 부분을 통제하지 않는다면요?API for Instant payment notification(IPN)을 코딩할 때 문제가 있었습니다.일반적인 규칙은 클라이언트 부분에 대한 정보를 얻으려고 시도하는 것입니다. 프런트 엔드 팀과 소통하고 결제 문서 페이지로 이동합니다.클라이언트 부분에서 결정한 내용 유형에 따라 적절한 미들웨어를 추가해야 할 수도 있습니다.
마지막으로 풀스택 개발자를 위한 조언입니다 :)
이와 같은 문제가 발생할 때는 포스트맨과 같은 API 테스트 소프트웨어를 사용해 보십시오.클라이언트 부분의 모든 노이즈를 제거하는 것이 목적이며, 이를 통해 문제를 정확하게 식별할 수 있습니다.
우체부에서 올바른 결과를 얻으면 소프트웨어의 코드 생성 도구를 사용하여 해당 코드를 가질 수 있습니다.단추</>오른쪽 바에 있습니다.인기 있는 언어/도서관에서 다양한 옵션을 선택할 수 있습니다.
app.use(express.json());
그것은 문제를 해결하는 데 도움이 될 것입니다.req.body되지 않음
// Require body-parser (to receive post data from clients)
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
바디 파서는 더 이상 익스프레스와 함께 배송되지 않는 것 같습니다.우리는 그것을 따로 설치해야 할 수도 있습니다.
var express = require('express')
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())
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
app.use(function (req, res, next) {
console.log(req.body) // populated!
자세한 정보 및 예제는 git 페이지 https://github.com/expressjs/body-parser 를 참조하십시오.
누군가 제가 겪고 있던 것과 같은 문제에 부딪힐 경우; 저는 다음과 같은 URL 접두사를 사용하고 있습니다.
http://example.com/api/
라우터와 함께 설정되었습니다.
app.use('/api', router);
그리고 나서 다음과 같은 것을 얻었습니다.
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
은 바디 에 배치한 입니다.app.use('/api', router);
최종
// setup bodyparser
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
//this is a fix for the prefix of example.com/api/ so we dont need to code the prefix in every route
app.use('/api', router);
대부분의 경우 JSON 파서가 누락되어 requ.body가 정의되지 않았습니다.
const express = require('express');
app.use(express.json());
시체 파서가 실종됐을 수도 있습니다
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
그리고 때로는 교차 원점으로 인해 정의되지 않았으므로 추가합니다.
const cors = require('cors');
app.use(cors())
미들웨어는 항상 첫 번째로 사용됩니다.
//MIDDLEWARE
app.use(bodyParser.json());
app.use(cors());
app.use(cookieParser());
항로 전에
//MY ROUTES
app.use("/api", authRoutes);
표현.bodyParser()에 구문 분석 중인 콘텐츠 유형이 무엇인지 알려야 합니다.따라서 POST 요청을 실행할 때 "내용 유형" 헤더를 포함해야 합니다.그렇지 않으면 BodyParser가 POST 요청 본문을 어떻게 처리해야 할지 모를 수 있습니다.
본문에 JSON 개체가 포함된 POST 요청을 실행하기 위해 컬을 사용하는 경우 다음과 같습니다.
curl -X POST -H "Content-Type: application/json" -d @your_json_file http://localhost:xxxx/someRoute
다른 방법을 사용하는 경우 적절한 규칙을 사용하여 헤더 필드를 설정해야 합니다.
라우팅하기 전에 app.use(bodyparser.json(); // . app.use("/api", routes);
기록:
이전 버전의 Express에는 많은 미들웨어가 번들로 제공되었습니다. bodyParser함께 제공된 미들웨어 중 하나입니다.Express 4.0이 출시되었을 때 그들은 번들 미들웨어를 Express에서 제거하고 대신 별도의 패키지로 만들기로 결정했습니다.그런 다음 구문이 에서 변경되었습니다.app.use(express.json())app.use(bodyParser.json()) 후bodyParser모듈.
bodyParser사람들이 이전처럼 Express와 함께 번들로 제공되기를 원했기 때문에 릴리스 4.16.0에서 Express에 다시 추가되었습니다.그 말은 당신이 사용할 필요가 없다는 것을 의미합니다.bodyParser.json()최신 릴리스에 있는 경우 더 이상 사용할 수 없습니다.사용할 수 있습니다.express.json()대신.
4.16.0의 릴리스 기록은 관심 있는 사용자를 위해 여기에 있으며, 풀 요청은 여기에 있습니다.
좋아요, 다시 본론으로 돌아가서,
구현:
당신이 추가해야 할 것은 그냥 추가하는 것입니다.
app.use(express.json());
app.use(express.urlencoded({ extended: true}));
app.use(app.router); // Route will be at the end of parser
거를 합니다.bodyParser이 필요하지 않습니다익스프레스필는서않요지습다니하에전버의최신)▁()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
그리고 익스프레스가 당신의 요청을 처리할 것입니다.:)
전체 예는 다음과 같습니다.
const express = require('express')
const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true}));
app.post('/test-url', (req, res) => {
console.log(req.body)
return res.send("went well")
})
app.listen(3000, () => {
console.log("running on port 3000")
})
다음 코드 줄을 맨 위에 추가할 수 있습니다(요구 사항 설명 후).
app.use(bodyParser.urlencoded({extended: true}));
작동하는 이유에 대해서는 문서를 확인하십시오. https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions
이 미들웨어를 하십시오.(express.urlencoded)항로 전에
let app = express();
//response as Json
app.use(express.json());
//Parse x-www-form-urlencoded request into req.body
app.use(express.urlencoded({ extended: true }));
app.post('/test',(req,res)=>{
res.json(req.body);
});
드express.urlencoded({extended:true})에 응니다합답▁responds에만 응답합니다.x-www-form-urlencoded 게시 요청, 즉 Ajax/X에 게시MLHttpRequest/fetch, 전송 중인지 확인합니다.request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');표제의
바로 그거야!
익스프레스 4에서는 정말 간단합니다.
const app = express()
const p = process.env.PORT || 8082
app.use(express.json())
오늘 저는 이런 생각이 들었습니다.위의 어떤 해결책도 저에게는 통하지 않습니다.하지만 약간의 구글 검색은 제가 이 문제를 해결하는 데 도움이 되었습니다.저는 wechat 제3자 서버를 위해 코딩을 하고 있습니다.
node.js 애플리케이션이 REST 클라이언트의 요청과 같이 스트리밍 POST 데이터를 읽어야 하는 경우 상황이 약간 더 복잡해집니다.이 경우 요청의 속성 "readable"이 true로 설정되고 모든 콘텐츠를 수집하려면 POST 데이터를 청크로 읽어야 합니다.
http://www.primaryobjects.com/CMS/Article144
많은 시간 낭비:
클라이언트 요청의 내용 유형에 따라 다름
서버는 다음 app.use() 중 하나와 달라야 합니다.
app.use(bodyParser.text({ type: 'text/html' }))
app.use(bodyParser.text({ type: 'text/xml' }))
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
app.use(bodyParser.json({ type: 'application/*+json' }))
출처: https://www.npmjs.com/package/body-parser#bodyparsertextoptions
예:
클라이언트 측에서는 다음과 같은 헤더를 사용했습니다.
Content-Type: "text/xml"
서버 측에서는 다음을 사용했습니다.
app.use(bodyParser.text({type: 'text/xml'}));
그 다음엔 신체가 정상적으로 작동했습니다.
도 같은 문제를 같은문생기서, ,▁i▁as만나알지,▁although,도▁problem▁the▁same.BodyParser더 이미 된 더이사사이용습니다했미않으며지용상되▁the다.app.use(express.json()) ME을(를) .
app.use(express.json())
끝나고
app.use('api/v1/example', example)=} => {경로 관련}
그 두 줄을 다시 주문하면,
1 -app.use(express.json())
2 -app.use('api/v1/example', example)
완벽하게 작동했습니다.
작업을 위해서는 app.use(express) 다음에 app.use(app.router)를 입력해야 합니다.bodyParser(), 다음과 같은.
app.use(express.bodyParser())
.use(express.methodOverride())
.use(app.router);
var bodyParser = require('body-parser');
app.use(bodyParser.json());
덕분에 목숨을 건졌습니다.
다음을 통해 해결 방법을 해결했습니다.
app.post('/', bodyParser.json(), (req, res) => {//we have req.body JSON
});
저 같은 경우에는 루트를 포함한 후 바디 파서를 사용했기 때문입니다.
올바른 코드는 다음과 같습니다.
app.use(bodyParser.urlencoded({extended:true}));
app.use(methodOverride("_method"));
app.use(indexRoutes);
app.use(userRoutes);
app.use(adminRoutes);
외부 도구를 사용하여 요청하는 경우 헤더를 추가해야 합니다.
Content-Type: application/json
이것도 한 가지 가능성입니다. app.js(또는 index.js) 파일의 경로 앞에 이 코드를 작성해야 합니다.
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
언급URL : https://stackoverflow.com/questions/9177049/express-js-req-body-undefined
'it-source' 카테고리의 다른 글
| 거부된 마스터 -> 마스터(비고속 포워드) (0) | 2023.05.26 |
|---|---|
| Xcode 소스 자동 포맷 (0) | 2023.05.26 |
| mongodb에서 삭제된 공간을 자동 압축하시겠습니까? (0) | 2023.05.26 |
| ActiveX 컨트롤이 비활성화되어 있습니까? (0) | 2023.05.26 |
| Eclipse Juno에서 "빠른 액세스" 항목 제거 (0) | 2023.05.26 |