如何使用托管在Heroku上的Angular App修复CORS?



我已经按照这篇文章(01.10.2019 12:15(在Heroku上部署了Angular App,实际上在我的笔记本电脑上工作得很好。

但是,在我的手机中打开请求不起作用。我正在使用 MEAN 堆栈。

基本上后端在节点快递中,它与MongoDB通信并处理文档。 我还在 Heroku 上托管了后端,它返回了一个类似"backend.appheroku.com"的链接。如果我在邮递员中运行它,例如,发出请求,它可以正常工作。我请求的是哪个设备并不重要(例如:GET backend.appheroku.com/users(。

当然,在FrontEndAngular App中,我创建了一个service.ts,以便我发出诸如GET,POST等请求。Heroku还返回了一个类似"frontend.appheroku.com">的链接。这在我的笔记本电脑中工作正常,但是,在我的手机中运行该链接,我无法再从前端应用程序发出请求。 例如"frontend.appheroku.com/users"从"backend.appheroku.com"/用户请求"用户"集合,并用HTML显示结果。

我只知道这是来自CORS问题,但是,我仍然没有找到解决方案。我也试图遵循 https://expressjs.com/en/resources/middleware/cors.html 的步骤,但没有成功。

后端.js文件:

var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/users', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
let port = process.env.PORT || 3050;
app.listen(port, function () {
console.log('CORS-enabled web server listening on Heroku port')
})

提前谢谢。

我不得不在后端添加下面的代码.js(谢谢@fridoo(:

app.options('*', cors()) // include before other routes

在package.json中,我还必须添加"heroku-postbuild":"ng build --prod">

{
"postinstall": "ng build --aot --prod",
"heroku-postbuild": "ng build --prod" // add this for heroku
},

最新更新