当你的站是一个静态网站时,并且网站中有接口请求时,可能会出现跨域问题。那解决该问题的大部分的办法就是使用一个服务器做代理转发。
所以说到这就知道,还需要一个服务器,即:要花钱。那有什么办法吗?
说出来了当然有。
使用 vercel 托管你的静态网站。
在你的项目根目录创建一个 vercel.json 文件,内容如下:
{
"rewrites": [
{
"source": "/notion-api/(.*)",
"destination": "/api/proxy"
}
]
}
这个地址是在 vercel 上启动一个常驻服务生成的。
在项目根目录创建一个 api/proxy.js 路径的文件,按照这个路径要求来,该文件的内容如下:
// req:请求
// res:响应
module.exports = (req, res) => {
// ...
}
然后在这个函数体内可以自己编写请求的转发。
看看我的写过的一个例子,用来转发 Notion API 接口。
完整例子:
const request = require('request');
module.exports = (req, res) => {
// proxy middleware options
let prefix = "/notion-api"
if (!req.url.startsWith(prefix)) {
return;
}
let target = "<https://api.notion.com>" + req.url.substring(prefix.length);
var options = {
'method': 'GET',
'url': target,
'headers': {
'Notion-Version': res.headers['notion-version'],
'Authorization': res.headers['authorization']
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
res.writeHead(200, {"Content-Type": "application/json"});
res.write(response.body);
res.end();
});
}
该例子,就是从 req
参数里获取想要的数据,然后使用 request
发放进行转发。