nextjs14 跨域该如何处理

next.config.jsnext.config.mjs他有什么区别

next.config.js:

  • 使用的是 CommonJS 模块系统
  • 这是 Next.js 默认的配置文件格式,也是大多数情况下使用的格式。
  • 使用 require 语法导入模块,使用 module.exports 导出对象。

next.config.mjs:

  • 使用的是 ES Modules (ESM) 模块系统
  • 这是较新的模块系统,它提供了更现代化的语法和功能。
  • 使用 import 语法导入模块,使用 export 语法导出对象。

解决方法

我项目是next.config.mjs原理都差不多一样了

Config 配置

  • next.config.mjs
/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: false, // 严格模式
};

// 请求头配置
nextConfig.headers = async  () => {
  return [
    {
      source: '/api/:path*',
      headers: [
        { key: 'Access-Control-Allow-Credentials', value: 'true' },
        { key: 'Access-Control-Allow-Origin', value: '*' },
        { key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT' },
      ]
    }
  ]
}

// 跨域配置
nextConfig.rewrites = async () => {
  return [
    {
      source: '/api/:path*', // ✨
      destination: 'https://api.google.com/:path*',
    },
  ]
}

export default nextConfig;
  • next.config.js
module.exports = {
  async rewrites() {
    return [
      {
        source: '/api/:path*', // ✨
        destination: 'https://api.google.com/:path*'
      }
    ];
  },
  async headers() {
    return [
      {
        // matching all API routes
        source: '/api/:path*',
        headers: [
          { key: 'Access-Control-Allow-Credentials', value: 'true' },
          { key: 'Access-Control-Allow-Origin', value: '*' },
          { key: 'Access-Control-Allow-Methods', value: 'GET,OPTIONS,PATCH,DELETE,POST,PUT' },
          { key: 'Access-Control-Allow-Headers', value: 'X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version' },
        ],
      },
    ];
  },
}

axios 配置

我这里用的是axios

  • axios.ts
import Axios, {
  type AxiosInstance,
  type AxiosRequestConfig,
  type CustomParamsSerializer
} from "axios";

// 相关配置请参考:www.axios-js.com/zh-cn/docs/#axios-request-config-1
const defaultConfig: AxiosRequestConfig = {
  baseURL:'/api', // ✨ 地址就这个了
  // 请求超时时间
  timeout: 10000,
  headers: {
    // Accept: "application/json, text/plain, */*",
    // "Content-Type": "application/json",
    // "X-Requested-With": "XMLHttpRequest"
  },
};

参考

  • 其他执行百度谷歌
posted @ 2024-08-07 15:31  天使阿丽塔  阅读(13)  评论(0编辑  收藏  举报