Home > Blockchain >  Express: req.query is always empty
Express: req.query is always empty

Time:12-09

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');
    });
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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="[email protected]" required>

        <label for="password">Password</label>
        <input type="password" id="password" name="password" required>

        <button type ="submit">Submit</button>
    </fieldset>
</form>

</body>
</html>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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)
});

CodePudding user response:

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'}

  • Related