【问题标题】:Angular Universal app can't make post requests to my Heroku node APIAngular Universal 应用程序无法向我的 Heroku 节点 API 发出发布请求
【发布时间】:2018-12-17 04:18:23
【问题描述】:

我的网站是使用 Angular 构建的 SPA,但它使用 SSR 和 Angular Universal 来提供可抓取的社交媒体共享内容。

我服务器中的所有 GET 请求都由 Universal 处理,如下所示:

app.engine(


'html',
  ngExpressEngine({
    bootstrap: ServerAppModuleNgFactory,
    providers: [provider]
  })
)

app.set('view engine', 'html')
app.set('views', __dirname)

app.use('/', express.static('./dist', {index: false}))
app.use('/', expressStaticGzip('./dist', {
  enableBrotli: true
}))

app.get('/*', (req, res) => {
    res.render('./dist/index', {
        req: req,
        res: res
    })
})

我的页面内容由 Angular Services POST 请求提供,该请求使用与请求的 url 相同的 queryParams 构建。

一个例子:

如果用户访问 url https://mywebsite.com/products?page=1&itemsPerPage=12(默认为 GET 请求),Angular Universal 应用程序和 Angular 路由器会动态构建我的页面模板,并且产品列表由触发对该 URL 的 POST 请求的服务提供: https://mywebsite.com/request-products 在正文中带有以下参数:

{
    page: 1,
    itemsPerPage: 12
}

然后通用应用程序使用一些 *ngFor 指令构建模板,以在将其提供给客户端之前填充它。

这种方法使我的所有页面都对网络爬虫可见,而且我还获得了单页应用程序的好处。

当我测试我的应用程序时,我构建了我的 Angular 应用程序,包括浏览器和服务器构建,并像这样设置我的环境:

export const environment = {
  production: true,
  apiUrl: 'http://localhost:7070/'
}

并在 localhost 中为我的应用程序提供服务,它运行良好,没有错误。如前所述,我的 POST 请求都得到了完美的处理。但是,当我尝试将我的 apiUrl 设置为“https://mywebsite.com/”并在 localhost 中提供我的应用程序以直接访问托管在 Heroku 中的 API 时,我无法访问我的 POST 路由。

我在 Heroku 中的 node express 服务器应用程序被配置为接受来自其他域的请求,我可以在我的 localhost 服务器中正常访问它,但是当我尝试通过我的 Angular Universal 服务器构建访问它时,它就无法工作。

我知道我必须在我的通用应用程序中使用绝对 URL,我已经这样做了,但它不起作用。

有谁知道我必须做什么才能通过 https 访问我的 Angular 通用应用程序中的外部 API?

谢谢!

【问题讨论】:

    标签: node.js angular express server-side-rendering angular-universal


    【解决方案1】:

    我发现了问题,而且很简单。

    事实证明,我必须在绝对网址中使用“www”,如下所示:

    'https://www.mywebsite.com/'

    现在一切正常,无论是从我的本地主机还是我的 heroku 服务器。

    感谢所有花时间阅读我的问题的人!

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 1970-01-01
      • 2021-01-27
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 2018-01-29
      • 2021-09-03
      • 2021-08-11
      相关资源
      最近更新 更多