在digitalocean中部署MERN堆栈应用程序时, CORS请求不成功



我有两个服务器在运行。react前端运行在端口3000上,express后端运行在端口8000上。前端向后端发出请求,但请求返回CORS错误。这个问题只发生在数字海洋服务器上。

来自react应用的请求:

await Axios.get("http://localhost:8000/api").then(         
(response) =>{
setListOfArticles(response.data);
setIsLoading(false)
},

)

表达后端:

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next(); });

我已经阅读了关于这个主题的多个答案,并试图用0.0.0.0:8000改变localhost:8000,但没有成功。

当添加:

app.use(express.static(path.join(__dirname, '../front/build')))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../front/build'))
})

到express后端并在浏览器中打开它,出现相同的错误。

你知道为什么会这样吗?请注意,这个应用程序在我的电脑上运行得很完美。

我不明白你为什么在端口3000上运行你的前端服务器,除非你做服务器端渲染。如果你只是有一个传统的单页应用程序,你必须通过Nginx甚至express来构建和提供文件。

使用Nginx服务你的express应用和react应用。下面的链接可能会有帮助。

https://javascript.plainenglish.io/how-to-deploy-a-react-app-with-expressjs-and-nginx-29abeef08c67

你不能硬编码localhost:8000到你的react应用程序。

await axios.get("/api").then(         
(response) =>{
setListOfArticles(response.data);
setIsLoading(false)
},

)

最新更新