我在 Heroku 服务器上运行应用程序时遇到问题;尽管在本地一切正常。 我希望一些专家或第二双眼睛能指出我可能遗漏的东西。
一个应用程序是一个服务器,这是代码:
const express = require('express'),
server = express(),
cors = require('cors');
server.use(cors({origin: "https://client-fox-67890fghij.herokuapp.com/"}));
server.get('/json-data', (req, res) => {
res.status(200).send([
{order:1,value:2},
{order:10,value:29}
])
});
另一个应用程序是客户端(Next.JS),这是代码:
app/page.tsx 文件:
import Receiver from './components/Receiver'
export default function Home() {
return (
<main className="flex min-h-screen flex-col items-center justify-between p-24">
<div>
<Receiver />
</div>
</main>
)
}
app/components/Receiver.tsx 文件:
'use client'
import {useState,useEffect} from "react"
import ListShow from './ListShow'
function Receiver() {
const [data, setData] = useState([]);
// const apiURL = 'http://localhost:8888/json-data'
const apiURL = 'https://server-wolf-12345abcde.herokuapp.com/json-data'
useEffect(() => {
let ignore = false;
async function fetchData() {
const result = await fetch(apiURL);
if (!ignore) setData(await result.json());
}
fetchData();
return () => { ignore = true; }
}, []);
return <><ListShow dataList={data}/></>;
}
export default Receiver;
上传两个应用程序并通过将网络浏览器指向以下位置来检查服务器端是否按预期响应:
https://server-wolf-12345abcde.herokuapp.com/json-data
当我将浏览器指向:
https://client-fox-67890fghij.herokuapp.com/
我在 Firefox 的 Web 开发人员工具控制台中遇到此错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://server-wolf-12345abcde.herokuapp.com/json-data. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘https://client-fox-67890fghij.herokuapp.com/’).
Uncaught (in promise) TypeError: NetworkError when attempting to fetch resource.
服务器本地运行在 localhost:8888 上,客户端运行在 localhost:3000 上。
然后在我使用的服务器中:
server.use(cors({origin: "http://localhost:3000"}));
为什么当服务器和客户端托管在 Heroku 上时它不再工作?
正如错误所示,URL 不匹配。像 Heroku 这样的服务通常会在重新部署时提供不同的 URL,看起来就是这样。对于这种情况,努力修复 CORS 可能不是最好的方法。我认为您应该在 Next 应用程序中调用一个 API,将调用转发到另一个 URL。类似于带有
的
app/json-data/route.ts
文件
export async function GET() {
const res = await fetch('https://server-wolf-12345abcde.herokuapp.com/json-data')
const data = await res.json()
return Response.json({ data })
}
并且,在您的
Receiver.tsx
中更改为
async function fetchData() {
const result = await fetch('/json-data');
if (!ignore) setData(await result.json());
}