简体   繁体   中英

Express JS POST Request

I'm trying to do a basic POST Request which stores the email address in a variable and then displays it in the console. The URL for the page is: http://localhost:3000/email-adress (I know it's missing an extra d on address).

For some reason the code isn't working, thoughts?

Express

const express = require('express')
const router = express.Router()

router.post('/email-adress', (req, res) => {
  var email = req.body.email
  console.log(email)
})

module.exports = router

HTML

<form action="/finished" method="post">
<label class="" for="email">Email address</label>
<input class="" id="email" name="email" type="text">
<button type="submit" class="">Continue</button>  
</form>

There's a few things here. First, when someone navigates to a url, in your example localhost:3000/email-adress (which only works on your machine by the way), the browser is making a GET request to the /email-adress route. I'm not sure what the rest of your express code is, but you'll have to have a route to handle this to assumably serve your form. Now, with the form served to the front end, if you want to trigger the code in the POST route to /email-adress , you will have to do that via fetch .

I'm assuming you want this to happen once you submit your form. In order to do that, handle the form's submission via JavaScript. Get rid of the action and method attributes, and do something like this:

document.querySelector('form').addEventListener('submit', onSubmit)

function onSubmit(e) {
  fetch('/email-adress', {
    method: 'POST',
    body: JSON.stringify({ email: e.target.email.value })
  })
}

Now, once you submit the form, you should see a console.log happen on your server.

I've worked out the answer thanks to Jaxi. What I was doing was doing the POST on the /email-adress rather than the /finished so I've amended the Express code to:

const express = require('express')
const router = express.Router()

router.post('/finished', (req, res) => {
  var email = req.body.email
  console.log(email)
  res.render('finished')
})

module.exports = router

That solved the problem!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM