[英]node.js & express: req.body undefined
我目前正在使用 express 設計一個簡單的瀏覽器應用程序。 我正在嘗試提取用戶在下拉菜單中選擇的值。 我也給每個選項一個單獨的值,並將表單的方法聲明為 /post。 但是當我通過進入req.body
嘗試他們選擇的值時,該值未定義。
我認識到問題可能在於身體解析器瀏覽類似問題( Example , Example1 ),但這些問題的解決方案並不能阻止req.body
未定義。
這是我的應用程序構建代碼
const app = express()
app.use(express.static(__dirname, ''));
app.engine('html', require('ejs').renderFile);
app.set('views', __dirname + '/public/views');
app.use(express.urlencoded());
app.set('view engine', 'html');
const server = http.createServer(app);
這是后處理的代碼
app.get('/detailed', function(req,res){
res.send(displayDetailed(results, req));
});
app.post('/detailed', function(req,res){
res.send('Hello world');
console.log(req.body);
});
當我在 localhost:8080/detailed 中發布內容時,hello world 返回得很好,但 req.body 為空(返回為 {})。 displayDetailed 函數是一個自定義函數,它返回一個 html 字符串,其中包含從 google 表格 API 的 get 請求中提取的值。 由於我沒有使用已保存的 html 文檔,這會影響流程嗎?
大多數時候 req.body 由於缺少 JSON 解析器而未定義
const express = require('express');
app.use(express.json());
身體解析器可能會丟失
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));
有時由於 cro 來源而未定義,因此添加它們
const cors = require('cors');
app.use(cors())
您是否設置了正文解析器以供 express 使用? 你可以 npm install body-parser 然后把它們放到你的代碼中。
const bodyParser = require('body-parser')
app.use(bodyParser.json())
希望這可以幫助!
在 async 函數之外調用req.body
時(調用構造 html 的函數的地方), req.body
返回完美無缺。 我將修改我的項目來解決這個問題。 我應該把它放在最初的問題中,但在我寫這個問題時它似乎並不相關。 感謝大家的回應
這將解決您的問題:
App.use(bodyParser.urlencoded({extended: true}));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.