前言

在客户端使用Nuxt的useFetch调用接口并存储cookie,发现一些趣事~

cookie存储需要遵守同源策略~ 理论我们是知道的,但具体是怎么一回事呢~

实现

在Nuxt中是这样的~

直接访问

Nuxt

<template>
    <div>{{ data }}</div>
</template>

<script setup lang="ts">
const { data } = await useFetch('http://localhost:9090/getUserInfo', {
    method: "POST",
    body: {
        name: "xxx"
    },
    server: false,
    
})

</script>


Express

const express = require("express")
const cookieParser = require("cookie-parser")
const cors = require("cors");
const app = express()
const PORT = 9090

app.use(cors());
app.use(cookieParser())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.post('/getUserInfo', (req, res) => {
    const { name } = req.body
    res.cookie('name', '张三', { httpOnly: true })
    res.send({
        text: `哎呀 ${name}你干嘛~`
    })
})

app.listen(PORT, () => {
    console.log(`listening on ${PORT}`);
})


效果 

 直接访问是存储不了cookie,因为不同源~

浅聊Cookie_nuxt

代理

Nuxt

<template>
    <div>{{ data }}</div>
</template>

<script setup lang="ts">
const { data } = await useFetch('/api/getUserInfo', {
    method: "POST",
    body: {
        name: "xxx"
    },
    server: false,
    
})
</script>


nuxt.config.ts 

// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
  devtools: { enabled: true },
  modules: [
    '@nuxt/content',
  ],
  vite: {
    server: {
      proxy: {
        '/api': {
          target: 'http://localhost:9090',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    }
  }
})


效果 

浅聊Cookie_nuxt_02

最后

Cookie需要遵守同源策略哦~