简体   繁体   English

尝试使用react JS发送帖子请求时,未认证用户

[英]User not being authenticated, when trying to send a post request using react JS

I am following a video tutorial which shows how to authenticate a user using node and passport JS. 我正在观看一个视频教程,该视频教程显示了如何使用节点和通行证JS对用户进行身份验证。 This tutorial uses Hogan JS for as its view engine, however I want to follow the tutorial using React as my front end, everything works fine on the server side, if I test it with postman, ie, the user is authenticated, serialized, deserialized and the session gets stored, but as soon as I try it while accessing it from my react, The user does not get authenticated even though I am getting a correct user at the serialize function. 本教程使用Hogan JS作为其视图引擎,但是我想使用React作为我的前端,如果我使用邮递员对其进行测试(即用户已通过身份验证,序列化,反序列化),则一切在服务器端都可以正常运行并且存储了会话,但是当我从我的反应访问它时,只要尝试它,即使在序列化功能中找到了正确的用户,该用户也不会得到认证。

Here is my server file: 这是我的服务器文件:

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const bodyParser = require('body-parser');
require('./passport');

express()
  .use(bodyParser.json())
  .use(bodyParser.urlencoded({extended: false}))
  .use(session({ secret: 'i love dogs', resave: false, saveUninitialized: false }))
  .use(passport.initialize())
  .use(passport.session())
  .get('/', (req, res, next) => {
    res.json({
      session: req.session,
      user: req.user,
      authenticated: req.isAuthenticated()
    });
  })
  .get('/login', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    res.json({name: 'login again'});
  })
  .post('/login', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
    next();
  }, passport.authenticate('local', {
    successRedirect: '/',
    failureRedirect: '/login'
  }))
  .listen(3001)
;

Here is my Passport file: 这是我的护照文件:

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const mongo = require('./db');
const ObjectId = require('mongodb').ObjectId;

passport.use(new LocalStrategy(authenticate));

function authenticate (email, password, done) {
  mongo.db.collection('users').find({email}).toArray((err, user) => {
    if (err) return done(null, false, {message: err});
    if (user.length === 0 || user[0].password !== password) {
      return done(null, false, {message: 'Invalid user and password combination'});
    }
    done(null, user);
  });
}

passport.serializeUser((user, done) => {
  done(null, user[0]._id);
  console.log(user);
});

passport.deserializeUser((id, done) => {
  console.log(id);
  mongo.db.collection('users').find({_id: ObjectId(id)}).toArray((err, user) => {
    if (err) return done(null, false, {message: err});
    done(null, user);
  });
});

and here is the react login component: 这是react登录组件:

import React, {Component} from 'react';

export default class Login extends Component {
  constructor (props) {
    super(props);

    this.onFormSubmit = this.onFormSubmit.bind(this);
  }

  onFormSubmit (e) {
    e.preventDefault();
    const { username, password } = this.refs;
    fetch(`http://localhost:3001/login?username=${username.value}&password=${password.value}`, {
      method: 'post'
    })
      .then(blob => blob.json())
      .then(res => {
        console.log(res);
      });
  }

  render () {
    return (
      <form onSubmit={this.onFormSubmit}>
        <div>
          <label>Email:</label>
          <input type='text' ref='username' />
        </div>
        <div>
          <label>Password:</label>
          <input type='password' ref='password' />
        </div>
        <div>
          <input type='submit' value='Log In' />
        </div>
      </form>
    );
  }
}

For the complete link of my project, here's the Github Link 对于我项目的完整链接,这是Github链接

Wow, I just figured out the answer,I just had to include: 哇,我只想出了答案,只需要包括:

credentials: 'include',

in the fetch method, and the set the headers to allow my server origin and set the allow credential headers to be true, here's how I did it: 在fetch方法中,将标头设置为允许我的服务器起源,并将allow凭据标头设置为true,这是我的操作方法:

res.header('Access-Control-Allow-Origin', 'http://localhost:3000');
res.header('Access-Control-Allow-Credentials', true);

This took me a whole day to get to this solution. 我花了一整天的时间来解决这个问题。

暂无
暂无

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

相关问题 尝试从 React 向 Node 发送 post 请求时代理请求错误,代理在获取请求时工作正常 - Proxy request error when trying to send post request from React to Node, proxy is working fine on get requests 使用 React 将 csv 文件作为用户的输入,并使用 axios 将其作为发布请求发送 - take a csv file as input from user using React and send it as a post request using axios 尝试将生成的PDF文件从React Js发送到Django-Rest Post请求时,未提交任何文件 - No file was submitted when try to send generated PDF file from React Js to Django-Rest Post request 即使在 Cypress 中尝试将 pdf 文件作为多部分 FormData POST 请求发送时,FormData 对象也是空的 - FormData object is empty even though it is being set when trying to send a pdf file as a multipart FormData POST request in Cypress 节点js-尝试发送POST请求,但未加载javascript内容 - Node js - Trying to send POST request, but it is not loading javascript content 尝试使用 axios POST 请求将信息发送到数据库时,如何解决此 422 错误? - How can I solve this 422 error when trying to send information to the database using an axios POST request? 为什么我在尝试使用 axios 发送发布请求时遇到网络错误 - Why i'm getting a network error, when trying to send a post request using axios 在 React-Native 中尝试 POST 请求时网络请求失败 - Network request failed when trying POST request in React-Native 如何发送 POST 请求以响应 node.js Express? - How to send a POST request in react to node.js Express? 如果用户重新加载/重定向页面,js发送发布请求 - js send post request if user reloads/redirect page
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM