简体   繁体   English

为什么我无法在我的 POST 请求中查看 req.body?

[英]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.我正在尝试通过 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.因为 passport-local 从 req.body 读取用户名和密码req.body ,所以我想确保我通过客户端正确地通过req.body传递它们。

When I run the following code, however, I get and empty object in the console:但是,当我运行以下代码时,我会在控制台中获取并清空 object:

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?谁能告诉我为什么我得到一个空的 object 而不是提供的用户名和密码?

Here is the React component I am working from:这是我正在使用的 React 组件:

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.我的 LocalStrategy 充满了虚拟代码。 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. @jonrsharpe 的建议让我找到了它。

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))
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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