简体   繁体   中英

Why can't I view the req.body in my POST request?

I'm trying to send a username and password from a login through Passport.js. Because passport-local reads the username and password arguments from req.body , I want to make sure that I am properly passing them through the req.body through the client-side.

When I run the following code, however, I get and empty object in the console:

router.post('/login', (req, res) => {
  console.log(req.body)
  res.send()
})

Can anyone tell me why I am getting an empty object instead of the supplied username and password?

Here is the React component I am working from:

import { useState } from 'react';

export const Login = () => {
  const url = 'http://localhost:3000/auth/login'
  const postLogin = async (username, password) => {
    await fetch(url, {
    method: 'POST',
    body: JSON.stringify({
      username: username,
      password: password
    })
    })
    .then(data => console.log(data))
  }

  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');

  return (
    <form>
      <div>
        <label htmlFor="username" >Username:</label>
        <input 
        type="text" 
        className="form-control" 
        id="username" 
        onInput={e => setUsername(e.target.value)}
        />
      </div>
      <div>
        <label htmlFor="password">Password:</label>
        <input 
        type="password" 
        className="form-control" 
        id="password" 
        onInput={e => setPassword(e.target.value)}
        />
      </div>
      <button type="button" className="btn btn-primary" onClick={() => postLogin(username, password)}>Submit</button>
    </form>
  )
}

Here is the server-side code:

require('dotenv').config();
const express = require('express')
const router = express.Router()
const session = require('express-session');
const passport = require("passport");
const bodyParser = require("body-parser");


const LocalStrategy = require("passport-local").Strategy;

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

router.use(session({ 
  secret: process.env.SESSION_SECRET,
  resave: false,
  saveUninitialized: true
}));
router.use(passport.initialize())

passport.use('local', new LocalStrategy((username, password, done) => {
  const authenticated = username === "John" && password === "Smith";

    if (authenticated) {
      return done(null, { myUser: "user", myID: 1234 });
    } else {
      return done(null, false);
    }
}))

router.get('/login', (req, res) => {
  res.send('test GET /login')
})

router.post('/login', (req, res) => {
  console.log(req.body)
  res.send()
})

module.exports = router;

*Just as a note, the server-side code is still incomplete. I have LocalStrategy filled with dummy-code. I'm just trying to understand this before I keep building it.

I wanted to post the answer in case anyone else runs into this. @jonrsharpe's suggestion pointed me to find it.

The key was in the headers. This works:

const postLogin = async (username, password) => {
  await fetch(url, {
    method: 'POST',
    body: JSON.stringify({
      username: username,
      password: password
    }),
    // missing part
    headers: {'Content-Type': 'application/json'}
  })
  .then(res => res.json())
  .then(data => console.log(data))
}

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