簡體   English   中英

快遞:req.query 始終為空

[英]Express: req.query is always empty

我有一個大致如下所示的文件:

 const express = require('express'), cookieParser = require('cookie-parser'), http = require('http'), path = require('path'), bodyParser = require('body-parser'), app = express(), server = http.createServer(app); app.use(bodyParser.urlencoded({extended: true})); app.use(express.static(path.join(__dirname,'./pub'))); app.use(cookieParser()); app.get('/', (req,res) => { res.sendFile(path.join(__dirname,'./index.html')); }); app.post('/test', (req, res) => { console.log(req.query); //returns empty object even though it shouldn't // does other stuff here }); server.listen(3000, function() { console.log('server is listening on port: 3000'); });

調用 foo.bar/test.html?query=foobar 會返回一個 html 登錄表單,該登錄表單將請求發送到提交時的 /test 路由 - 我希望 Z78E6221F6393D1356681DB398F14CE 的查詢是上面的 {{} ,但它是空的。

除查詢字符串外,應用程序中的其他所有內容都按預期工作(登錄請求、保存 session 等)。

申請表:

 <.DOCTYPE html> <html lang = "en"> <head> <meta charset = "UTF-8"> <title>Login</title> </head> <body> <form action="/test" method="POST"> <fieldset> <label for="email">Email</label> <input type ="email" id="email" name="email" placeholder="abc@example.com" required> <label for="password">Password</label> <input type="password" id="password" name="password" required> <button type ="submit">Submit</button> </fieldset> </form> </body> </html>

使用html表單執行請求時,可以使用req.body訪問道具。 數據不是使用querystring發送的(因此它不會添加到 url),而是添加到請求有效負載中。

這是從請求中讀取數據的代碼。

app.post('/test', (req, res) => {
    console.log('in login:')
    console.log(JSON.stringify(req.body)); // use req.body since there's no querystring.
    res.status(200).send('Login succeeded for user ' + req.body.email)
});

以下是您可以嘗試的可能解決方案:

確保在測試 API 時使用POST方法,因為您在路由中使用了POST方法。

此外,API URL 的格式應為http://localhost:3000/user?name=Karliah 這應該打印{ name: 'Karliah'}

 app.get('/test', (req,res) => { app.set('source', req.query.source); res.sendFile(path.join(__dirname,'./pub/test.html')); });

將此插入問題中提到的文件會添加一個可以在 POST 請求中訪問的“源”變量:

 app.post('/test', (req, res) => { console.log(req.app.get('source')); //returns the value // does other stuff here });

我調用的 URL 不再使用.html:之前:foo.bar/test.html?source=12333之后:foobar.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM