DanCode
DanCode

Reputation: 673

Redirect response into a dynamic url

I am using node js with:

My task is to redirect my response to a url with a format /users/:name/course/:courseId.

After running the code with the parameters name=James and courseId=1234, I get /users/James/course/1234 in the browser url. However, I am not able to post to /users/James/course/1234.

Edit: the data is being successfully posted, but I am getting a message Cannot GET /users/James/course/1234.

I have the following code:

app.js:

app.get('/', (req, res) => {
    res.render('form.hbs')
})

app.post('/saveUsers', [
    // firstname must contain letters only
    check('firstname', 'First name should contain only letters').isAlpha(),
    // email must be in a email format
    check('email', 'Email field must be in a email format').isEmail(),
    // courseId must be numerical and exactly 4 digits
    check('courseId', 'course ID should contain only numbers').isNumeric(),
    check('courseId', 'course ID should be exactly 4 digits').isLength({ min: 4, max: 4 })
], (req, res) => {
    const errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array(), data:req.body})
    }
    var db = utils.getDb()
    db.collection('users').insertOne({
        name: req.body.firstname,
        email: req.body.email,
        courseId: req.body.courseId
    }, (err, result) => {
        if (err) {
            Response.send('Unable to insert a student')
        }
        console.log(result.ops)
        nameUrl = result.ops[0].name
        courseIdUrl = result.ops[0].courseId
        res.redirect(`/users/${nameUrl}/course/${courseIdUrl}`)
    })
})

app.post(`/users/${nameUrl}/course/${courseIdUrl}`, (req, res) => {
    res.json(result.ops)
})

form.hbs:

<!DOCTYPE html>
<html>
    <body>
        <h1>Welcome</h1>
        <p>Enter your name, email and course ID:</p>
        <form action="/saveUsers" method="POST" id="myForm">
            <input type="text" placeholder="firstname" name="firstname">
            <input type="email" placeholder="email" name="email">
            <input type="text" placeholder="courseId" name="courseId">
            <input type="submit" value="Submit">
        </form>
    </body>
</html>

Upvotes: 0

Views: 650

Answers (1)

Neil VanLandingham
Neil VanLandingham

Reputation: 1086

It looks like you are using template literal string interpolation where you should be using the Express syntax for route parameters. See the "route parameters" section in the docs.

Instead of:

app.post(`/users/${nameUrl}/course/${courseIdUrl}`, (req, res) => {
    res.json(result.ops)
})

Try:

app.post(`/users/:name/course/:courseId`, (req, res) => {
    res.json(result.ops)
})

Upvotes: 1

Related Questions