Express项目中Fetch请求遇Cross-Origin Request Blocked错误求助
解决跨域请求被拦截的问题
你的问题本质是浏览器同源策略限制,且该第三方API明确拒绝前端跨域请求(返回451状态码),另外直接把API_KEY写在前端代码里存在严重安全风险,绝不能用于生产环境。下面是两种解决方案:
方案一:通过Express后端代理请求(推荐)
让后端作为中间层调用第三方API,前端只请求自己的后端接口,这样既规避跨域问题,又能保护API密钥。
步骤1:安装依赖
在项目根目录执行:
npm install axios cors
步骤2:修改Express代码
const express = require("express") const axios = require("axios") const cors = require("cors") const app = express() // 允许跨域(前端请求后端时用,可选但更稳妥) app.use(cors()) // 解析表单格式的请求体 app.use(express.urlencoded({ extended: true })) // 前端页面路由 app.get("/",(req,res)=>{ res.sendFile("index.html",{root:__dirname}) }) // 新增代理路由,处理短链接请求 app.post("/shorten-url", async (req, res) => { try { const encodedParams = new URLSearchParams(); encodedParams.append("url", req.body.url); const response = await axios.post('https://url-shortener-service.p.rapidapi.com/shorten', encodedParams, { headers: { 'content-type': 'application/x-www-form-urlencoded', 'X-RapidAPI-Key': 'API_KEY', // 密钥仅后端可见,避免泄露 'X-RapidAPI-Host': 'url-shortener-service.p.rapidapi.com' } }) res.json(response.data) } catch (err) { res.status(err.response?.status || 500).json({ error: err.message }) } }) app.listen(4000,()=>{console.log("started on port 4000")})
步骤3:修改前端index.html代码
<!DOCTYPE html> <html lang="en"> <script> const encodedParams = new URLSearchParams(); encodedParams.append("url", "https://google.com/"); const options = { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: encodedParams }; // 请求自己的后端代理路由,而非直接调用第三方API fetch('/shorten-url', options) .then(response => response.json()) .then(response => console.log(response)) .catch(err => console.error(err)); </script> </html>
方案二:开发环境临时用CORS浏览器插件(仅测试用)
如果你只是本地开发测试,可以安装浏览器的CORS插件(如Chrome的CORS Unblock),启用后能临时绕过同源策略限制。但注意:
- 此方法仅适用于本地开发,绝对不能用于生产环境
- 前端代码里的API密钥仍然会暴露,存在被盗用风险
内容的提问来源于stack exchange,提问作者Mehan Alavi
相关产品推荐
相关产品推荐

