Next.js API路由重定向至Shopify链接出现CORS问题如何解决
问题根因
你当前触发CORS错误的核心原因是:通过axios发起异步POST请求时,浏览器会自动跟随服务端返回的3xx重定向响应,向Shopify的OAuth地址发起跨域异步请求,而Shopify的OAuth接口未配置允许你的站点跨域访问,因此会触发跨域报错,和你在Next.js API路由侧配置的CORS中间件无关。
修复方案
- 第一步:修改Next.js API路由逻辑,不再返回重定向响应,改为将Shopify授权地址以JSON形式返回给前端
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction const { checkHmacValidity } = require("shopify-hmac-validation"); import Cors from "cors"; import initMiddleware from "../../lib/init-middleware"; // Initialize the cors middleware const cors = initMiddleware( Cors({ methods: ["GET", "POST", "OPTIONS"], }) ); export default async (req, res) => { await cors(req, res); console.log("req.body", req.body); const test = checkHmacValidity(process.env.SHOPIFY_SECRET, req.body.query); if (test) { const nonce = req.body.query.timestamp; const authUrl = `https://website.myshopify.com/admin/oauth/authorize?client_id=${process.env.SHOPIFY_TOKEN}&scope=write_orders,read_customers&redirect_uri=http://localhost:3000/shopifyConfirm&state=${nonce}&grant_options[]=per-user` // 替换重定向逻辑,直接返回授权地址 res.status(200).json({ authUrl }) return } // 未通过校验返回403 res.status(403).end() };
- 第二步:修改前端axios请求逻辑,拿到授权地址后主动触发页面级跳转,页面级跳转不受CORS规则限制
axios({ method: "post", headers: { "content-type": "application/json" }, url: "/api/shopifyEntry", data: { query: Router.query, nonce: nonce, }, }) .then(function (response) { // 触发页面跳转 if (response.data?.authUrl) { window.location.href = response.data.authUrl } }) .catch(function (error) { console.log(error); });
额外优化建议
- state参数不要直接使用timestamp,建议生成随机字符串,存储到本地cookie或sessionStorage中,Shopify回调时校验state一致性,防止CSRF攻击
- 生产环境部署时需要将redirect_uri中的
localhost:3000替换为实际线上域名,和Shopify后台配置的回调地址保持完全一致
内容的提问来源于stack exchange,提问作者Anders Kitson
相关产品推荐
相关产品推荐

