简体   繁体   中英

retrieve data from a post request nodeJS

i have a super simple form

index.html:

<html>
  <body>
  PAGE
    <form method = "post" action="/login">
      pseudo: <input type="text" name="username"><br>
      mdp: <input type="password" name="password">
      <input type="submit" value="post">
    </form>
   </body>
</html>

and a server.js file:

 /******** Chargement des Middleware *********/
const bodyParser = require('body-parser');

 /******** Declaration des variables *********/

   /******** Configuration du serveur NodeJS - Port :  30002 *********/

const express = require('express');
const app = express(); // appel a expressJS
const server= app.listen(3116,function(){
 console.log('listening on port 3116');
});

 app.use(bodyParser.urlencoded({ extended: true }));
 app.use(bodyParser.json({limit: '10mb'}));

 /******** Gestion des URI ********/

  app.get('/', function(request, response) {
  response.sendFile('CERIGame/index.html',{ root:       __dirname });
   });

app.post('/login', function(req, res) {
  var username = req.body.username;
  var password = req.body.password;
  console.log("post received: %s %s", username,   password);
 });

i'm getting a "Cannot post /login" when i click on submit button and nothing in the console. any idea about what's wrong or missing please ?

I ran your code on my machine and found everything working except one issue, you have to return the response from the /login API. Please find the code for returning response from server below.

app.post('/login', function(req, res) {
  var username = req.body.username;
  var password = req.body.password;
  console.log("post received: %s %s", username,   password);
  return res.json({"success": 1})
 });

Just for your information when running on your local machine the web app should be at http://localhost:3116 .

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