![](/img/trans.png)
[英]Nuxt 3 - OpenAi api - Works locally but not when deployed (on Vercel)
[英]nuxt app deployed to Netlify: fetch to api working locally, but not on deployed site: getting a 404
我有一個 Nuxt.js 應用程序,我正在嘗試部署到 Netlify - 一切都在我的本地機器上運行,但是當它部署到 Netlify 時,對 api 的獲取請求返回 404。 我不知道如何在部署時使該服務器路由對我的客戶端可用。
我的 api-client.js 文件中的 fetch 請求如下所示:
async fetchInfo(state) {
let response = await fetch(`/api/info/${state}`);
let data = await response.json();
return data;
}
並且 api 看起來像這樣(在 api/index.js 文件中):
const rp = require('request-promise');
const apiKey = process.env.POLICY_API_KEY;
export default function (req, res, next) {
if (req.url.includes("/info")) {
let stateAbbr = req.originalUrl.slice(-2);
rp({
uri: `https://third-party-api-here.com/states/${stateAbbr}/`,
method: 'GET',
headers: {
'token': apiKey,
},
json: true
}).then(function success(response) {
if (response) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response));
return;
}
}).catch(function error(response) {
console.log('error', response.error);
});
return;
}
next();
}
我認為這可能與CORS有關? 當我嘗試在已部署的應用程序中點擊該路由時,我在瀏覽器中收到此錯誤: GET https://my-app-name.netlify.app/api/info/MN 404
SyntaxError: Unexpected token < in JSON at position 0
正如上面評論中提到的,您需要有某種 Node.js。
因此,托管在 Heroku 上修復了 OP 的問題(Netlify 僅適用於靜態文件)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.