【问题标题】:Can not get cookies in ReactJS with ViteJs无法使用 ViteJs 在 ReactJS 中获取 cookie
【发布时间】:2023-01-21 16:14:38
【问题描述】:

我有一个对 Nest JS 后端的获取请求。使用 CRA 发出请求,然后在我的浏览器中设置 cookie,但是尝试使用使用 ViteJs 生成的 React Js 发出请求,然后我的浏览器中没有收到任何 cookie。
问题:为什么我不能使用 Vite 和 React 获取 cookie,但使用 CRA 可以? cookie 是否仅适用于 CRA 工作时的本地主机,因为 VITE url 类似于 http://127.0.0.1:5173/ 但不像 CRA 中的本地主机?

【问题讨论】:

    标签: reactjs cookies vite


    【解决方案1】:

    将 DNS 默认结果顺序设置为逐字将用 localhost 替换 ip 地址,这应该允许您设置 cookie。

    设置 cookie 时,您发送请求的 url 和跨源 url 需要相同。由于 vite 具有不同的起始地址,因此会发生这种情况,但 CRA 不会发生这种情况。

    这是我的 vite 配置文件的代码:

        import { defineConfig} from "vite";
        import react from "@vitejs/plugin-react";
        import dns from 'dns'
    
        dns.setDefaultResultOrder('verbatim')
    
        // https://vitejs.dev/config/
        export default defineConfig({
            plugins: [react()],
            server: {
                host: "localhost",
                port: "3002",
            },
        }); 
    

    【讨论】:

      猜你喜欢
      • 2019-12-16
      • 1970-01-01
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2019-05-02
      • 2012-06-04
      • 2020-07-13
      • 1970-01-01
      相关资源
      最近更新 更多