【问题标题】:cookie is null when using reactjs as frontend and nodejs as backend使用 reactjs 作为前端和 nodejs 作为后端时 cookie 为空
【发布时间】:2022-06-19 21:34:03
【问题描述】:

ReactJS 代码

import axios from 'axios';
import {useEffect,useState} from 'react';
import ReactDOM from "react-dom/client";
import React from "react";


const App = () => {
    const [res,setRes] = useState(null)
    useEffect(() => {
        document.cookie='hello=3';
        axios.get('http://localhost:4000/hello').then(res1 => {
            setRes(res1.data)
        })
    },[])

    return (
        <div>
            {res}
        </div>
    );

}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
        <App />
);

Nodejs 代码

import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser'
import cookieParser from 'cookie-parser'

const PORT = 4000;
const app = express();

// cors
app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser())


app.get('/hello', (req, res) => {
    console.log(req.cookies) 
    res.send('This is from server!')

})


app.listen(PORT, () => {

    console.log('listening on port', PORT); // eslint-disable-line no-console
});

在 node.js 中的 console.log(req.cookies) 行它给出 [Object: null prototype] {} 什么问题?

【问题讨论】:

    标签: node.js reactjs


    【解决方案1】:

    您正在向其他域发送请求。如果您想通过该请求发送 cookie,则必须在请求选项中添加 withCredentials 属性。

    axios.get(
      'http://localhost:4000/hello',
      { withCredentials: true }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-27
      • 2019-01-05
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2018-10-06
      相关资源
      最近更新 更多