简体   繁体   中英

Problem with express server POST method and fetch, undefined values on a log in

Im learning how to make a very simple log in for a chrome extension im developing, I take a name and a password from two imput boxes and send them to a server using express POST method, but they are not defined when I print them. Heres the code:

The server.js:

let express = require('express');
let path = require("path");

let app = express();

app.use(express.json());

app.use(express.static(path.join(__dirname, '/CTRL')));

app.post('/CTRL', function(req, res) {
    var nombre = req.body.name;
    var passw = req.body.passw
    console.log('Nombre: ' + nombre + ' password: ' + passw);
    res.send('Nombre: ' + nombre + ' password: ' + passw);
});

app.listen('8000', function() {
    console.log('server corriendo puerto 8000');
  })

and the client:

let nombre = document.getElementById('User');
let contrasena = document.getElementById('Password');
let boton = document.getElementById('boton');

boton.addEventListener('click', sendData);

function sendData(){

    let nombreSTR = nombre.value
    let contrasenaSTR = contrasena.value

    fetch('http://localhost:8000/CTRL', {
      mode:'no-cors',
      method: 'POST',
      body: { name: nombreSTR, passw: contrasenaSTR },
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json'
      }
    });
  }

This is what I get in console:

server corriendo puerto 8000

Nombre: undefined password: undefined

You need to convert your object to string before send,

fetch('http://localhost:8000/CTRL', {
      mode:'no-cors',
      method: 'POST',
      body: JSON.stringify({ name: nombreSTR, passw: contrasenaSTR }),
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
});

Method 1:

fetch('http://localhost:8000/CTRL', {
    mode: 'no-cors',
    method: 'POST',
    body: `name=${nombreSTR}&passw=${contrasenaSTR}`, // https://stackoverflow.com/a/42312303/11343720
    headers: {
        Accept: 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
});

Method 2: // Using JQuery

$.post('http://localhost:8000/CTRL', {
        name: nombreSTR,
        passw: contrasenaSTR
    },
    function (data, status) {
        alert("Data: " + data + "\nStatus: " + status);
    });

Couple things you omitted here:

  1. Try to remove the slash from your folder URI. Try this: app.use(express.static(path.join(__dirname, 'CTRL')));

  2. And Most importantly,
    a. npm install --save body-parser
    b. var bodyParser = require('body-parser')
    c. app.use(bodyParser.json())

If you don't import bodyParser ExpressJS won't be able to parse the body of your request.

Here is the full server-code sample I think will work for you

const express = require('express');
const path = require("path");
const bodyParser = require("body-parser")

const app = express();

app.use(express.json());

app.use(express.static(path.join(__dirname, 'CTRL')));


app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, noauth");
  if (req.method === 'OPTIONS'){
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, OPTIONS");
    res.setHeader('Access-Control-Allow-Credentials', false);
    return res.status(200).json({});
  }
  next();
});

app.post('/CTRL', function(req, res) {
  var nombre = req.body.name;
  var passw = req.body.passw
  console.log('Nombre: ' + nombre + ' password: ' + passw);
  res.send('Nombre: ' + nombre + ' password: ' + passw);
});

app.listen('8000', function() {
  console.log('server corriendo puerto 8000');
})

I think that's all you need my friend.

Good luck!

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