How to set cookies express, react.js

后端 未结 2 1850
迷失自我
迷失自我 2021-01-13 13:22

I am building a login system using express for node.js and react.js. In my back-end when a user logs in, it creates a cookie. When I go to Network > Login I can see this:

相关标签:
2条回答
  • 2021-01-13 13:50

    Try to set on you index.js or app.js server side this:

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

    and in you client site add options like this:

    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)
      }
    }
    
    0 讨论(0)
  • 2021-01-13 13:55

    Do not forget to adjust cors middleware.

    Your node.js express code

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

    Your front-end code

    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;
    
    0 讨论(0)
提交回复
热议问题