You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决React-Vite应用对接Lumen API的CORS错误

CORS问题排查:特定POST路由触发错误,其余路由正常

我在Digital Ocean App Platform部署了React应用与PHP Lumen API,Lumen已开启CORS,但有两个用于接收参数并调用Postmark发送邮件的POST路由请求时触发CORS错误,其余路由均正常工作。

前端请求代码

POST请求函数

export const sendPaymentEmail = async(card_code, name, amount) =>{
    const instance = axios.create(
        {
            baseURL:'https://mwdomain.com/api/',
            headers:{
                "Content-type": "application/json"
            },
            withCredentials: true
        }
    )
    return await instance.post(`sendTopupEmail/?card_code=${card_code}&name=${name}&amount=${amount}`).then(
        response => response
    )
}

export const sendPaymentValidationEmail = async(card_code, name, url) =>{
    const instance = axios.create(
        {
            baseURL:'https://mwdomain.com/api/',
            headers:{
                "Content-type": "application/json"
            },
        }
    )
    return await instance.post(`sendTopupConfirmationLink/?card_code=${card_code}&name=${name}&url=${url}`).then(
        response => response
    )
}

请求调用逻辑

const sendTopUpEmail = (card_code, subscribername, amount) => {
        try {
            sendPaymentEmail(card_code, subscribername, amount).then(
                response => {
                    console.log(response)
                }
            )
        } catch (error) {
            console.log(error)
        }
    }

报错信息

Access to XMLHttpRequest at 'https://mwdomain.com/api/sendTopupEmail/?card_code=2&name='Nate'&amount=1' from origin 'https://mwdomain.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
index-c92ba9c7.js:217 
        
        
        POST https://mwdomain.com/api/sendTopupEmail/?card_code=2&name='Nate&amount=1 net::ERR_FAILED 301 (Moved Permanently)

已尝试的无效方案

在vite.config中配置代理:

server: {
    proxy: {
      '/API': {
        target: 'https://mwdomain.com',
        changeOrigin: true,
        secure: false,
        ws:true,
        
      },
      '/eapi': {
        target: 'https://mwdomain.com/api/',
          changeOrigin: true,
          secure: false,
          agent: new http.Agent()
    },
    }
  },

使用代理后的请求代码:

export const sendPaymentValidationEmail = async(card_code, name, url) =>{
    const instance = axios.create(
        {
            baseURL:'/eapi',
            headers:{
                "Content-type": "application/json"
            },
        }
    )
    return await instance.post(`/sendTopupConfirmationLink/?card_code=${card_code}&name=${name}&url=${url}`).then(
        response => response
    )
}

求解决这两个POST路由的CORS问题。

内容的提问来源于stack exchange,提问作者Nate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 22:25:35