繁体   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