I have a file that roughly looks like this:
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'); });
Calling foo.bar/test.html?query=foobar returns an html login form that sends the request to the /test route on submit - and I'd expect the output of the console.log above to be { query: "foobar }, but it's empty.
Everything else in the app works as intended (the request for the login, saving the session, etc) with the exception of the query string.
The request form:
<.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>
When doing a request using a html
form, the props can be accessed using req.body
. The data is not sent using querystring
(so it's not added to the url) but added to the request payload.
Here's code to read out the data from request.
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)
});
Here are the possible solutions that you can try:
Make sure when you test the API, you use POST method since you have used POST method in the route.
Also, the API URL should be of the form http://localhost:3000/user?name=Karliah
. This should print { name: 'Karliah'}
app.get('/test', (req,res) => { app.set('source', req.query.source); res.sendFile(path.join(__dirname,'./pub/test.html')); });
Inserting this to the file mentioned in the question adds a "source" variable that can be accessed in the POST request:
app.post('/test', (req, res) => { console.log(req.app.get('source')); //returns the value // does other stuff here });
The URL I call does not use the.html anymore: before: foo.bar/test.html?source=123 after: foo.bar/test?source=123
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.