如何设置cookie express.react.js

时间:2018-12-22 17:50:09

标签: node.js reactjs express

我正在使用express构建node.js和react.js的登录系统。在我的后端,当用户登录时,它将创建一个cookie。当我转到“网络”>“登录”时,可以看到以下内容:

Set-Cookie:user_id = s%3A1.E%2FWVGXrIgyXaM4crLOoxO%2Fur0tdjeN6ldABcYOgpOPk;路径= /; HttpOnly;安全

但是当我转到“应用程序”>“ Cookies”>“ http://localhost:3000”时,那里什么也没有。我认为这是因为我在从客户端发出发布请求时不允许凭据正确通过。我该怎么办?请让我知道我是否可以以任何方式改善我的问题。

            //Login back-end
            router.post('/login', (req, res, next) => {
                if(validUser(req.body)) {
                    User
                        .getOneByEmail(req.body.email)
                        .then(user => {
                            if(user) {
                                bcrypt
                                    .compare(req.body.password_digest, user.password_digest)
                                    .then((result) => {
                                        if(result) {
                                            const isSecure = process.env.NODE_ENV != 'development';

                                            res.cookie('user_id', user.id, {
                                                httpOnly: true,
                                                secure: isSecure,
                                                signed: true
                                            })
                                            res.json({
                                                message: 'Logged in'
                                            });
                                        } else {
                                            next(new Error('Invalid Login'))
                                        }
                                    });
                            } else {
                                next(new Error('Invalid Login'))
                            }
                        });
                } else {
                    next(new Error('Invalid Login'))
                }
            });

            //Allow CORS index.js
            app.use(
            cors({
                origin: "http://localhost:3000",
                credentials: true
            })
            );

            //Login client side (React.js)
            loginUser(e, loginEmail, password) {
            e.preventDefault();

            let email = loginEmail;
            let password_digest = password;
            let body = JSON.stringify({ email, password_digest });

            fetch("http://localhost:5656/api/login", {
                method: "POST",
                headers: {
                "Content-Type": "application/json"
                },
                credentials: "include",
                body
            })
                .then(response => response.json())
                .then(user => {
                console.log(user);
                });
            }

2 个答案:

答案 0 :(得分:1)

尝试在您的index.js或app.js服务器端进行以下设置:

  app.use(function(req, res, next) {
  res.header('Content-Type', 'application/json;charset=UTF-8')
  res.header('Access-Control-Allow-Credentials', true)
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  )
  next()
})

并在您的客户端站点中添加以下选项:

let axiosConfig = {
  withCredentials: true,
}

export async function loginUser(data) {
  try {
    const res = await axios.post(
      `${URL}:${PORT}/${API}/signin`,
      data,
      axiosConfig
    )
    return res
  } catch (error) {
    console.log(error)
  }
}

答案 1 :(得分:0)

别忘了调整cors中间件。

您的node.js表达代码

const express = require("express");
const cors = require('cors')

const app = express();

app.use(cors(
  {
    origin: 'http://localhost:3000',
    optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
  }
));

app.use(function(req, res, next) {
  res.header('Content-Type', 'application/json;charset=UTF-8')
  res.header('Access-Control-Allow-Credentials', true)
  res.header(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  )
  next()
})

app.get("/auth", function(req, res){

  res.cookie('token', 'someauthtoken')
  res.json({id: 2});
});

app.listen(3030);

您的前端代码

import React, { useEffect } from 'react';
import axios from 'axios';


async function loginUser() {
  try {
    const res = await axios.get(
      'http://localhost:3030/auth',
      {
        withCredentials: true,
      }
    )
    return res
  } catch (error) {
    console.log(error)
  }
}

function App() {

  useEffect(() => {
    loginUser();
  }, [])

  return (
    <div>

    </div>
  );
}

export default App;