【问题标题】:Angular Route Displays Raw JSON on Browser RefreshAngular Route 在浏览器刷新时显示原始 JSON
【发布时间】:2019-05-03 16:34:33
【问题描述】:

我正在构建一个 MEAN 堆栈应用程序。我已经为开发设置了代理配置。我成功地从 Angular/Node 调用 API,但是当我刷新浏览器时,Angular 路由会显示我的原始 JSON 数据,如下所示:

在 StackOverflow 上没有太多关于这个特定问题的细节。我 99% 确定这是我如何设置 Angular 和 Node 路由的问题,但我不确定我做错了什么。

proxy.config.json

{
  "/**": {
    "target": "http://localhost:3000",
    "secure": false,
    "logLevel": "debug",
    "changeOrigin": true
    }
}

我的 Angular 路线

const APP_ROUTES: Routes = [
    { path: '', component: MainComponent },
    { path: 'homeaway/search', component: ResultsComponent }
];

Angular 服务方法

  searchListings(trip) {
    console.log("search listing", trip)

    //Grab all of the params from the trip argument and append them to params variable
    let params = new HttpParams()
    Object.keys(trip).forEach(function (key) {
     params = params.append(key, trip[key]);
    });

    const headers = new HttpHeaders()
    .set('Content-Type', 'application/json')

    const options = {
      headers: headers,
      params: params
    }

    return this.http.get(`/homeaway/search`, options) <-- MY GET CALL
    .pipe(
      map((res: Response) => res),
      catchError(error => throwError(error.message || error))
      )

  }

节点服务器信息

var homeAwayRouter = require('./routes/homeaway');
app.use('/homeaway', homeAwayRouter)

我的节点路由

router.get('/search', (req,res,next)  => {

    let params = {
      availabilityStart: req.query.availabilityStart,
      availabilityEnd: req.query.availabilityEnd,
      minSleeps: req.query.minSleeps,
      centerPointLatitude: req.query.centerPointLatitude,
      centerPointLongitude: req.query.centerPointLongitude,
      distanceInKm: req.query.distanceInKm
    }

    axios.get(searchURL, options, params)
      .then(function (response) {
        console.log('Successful HomeAway search in server /search', response);
        res.send(response.data); //Send data
      })
      .catch(function (error) {
        console.log(error);
      })

  });

结果组件

调用服务方法的地方

ngOnInit() {

    //Query params-based search on page init
    this.activatedRoute.queryParams.subscribe(params => {
         this.homeAwayService.searchListings(params).subscribe((res) => {
             this.searchResults = res
             console.log("response in activatedRoute in results", this.searchResults)
         });
  })

}

包.json

"scripts": {
    "ng": "ng",
    "start": "concurrently \"npm run serve-api\" \"npm run serve\"",
    "serve": "ng serve --proxy-config proxy.config.json",
    "serve-api": "nodemon server/app.js --watch server",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },

我尝试过的一些事情:

  • 将 Angular 路由 URL 更改为仅匹配“homeaway”或“search”
  • 更改 proxy.config url 以匹配“/homeaway”。虽然我想要 可用于我需要发出的任何后端 url 请求的路径。

所有这些都会导致 404 错误。

澄清一下:我成功获取了 API 数据,并且我的 URL 最初可以正常工作。页面刷新显示原始 JSON 而不是我的 Angular/HTML。

我对 MEAN 堆栈路由还很陌生,所以我希望能得到一些帮助来弄清楚这一点并了解为什么会发生这样的事情。感谢您的观看。

编辑:我想这可能是因为我的 Angular 和 Node 路由('/homeaway/search')相互匹配,但我不确定为什么会导致问题。当我尝试更改节点或 Angular 路由以使其不匹配时,我得到 404。

【问题讨论】:

  • 您是否在节点服务器上构建并部署了 Angular 应用程序?

标签: node.js angular express mean-stack


【解决方案1】:

如果您已经为您的 Angular 应用程序进行了构建,您可能需要在您的一个应用程序中更改路由。这里可能发生的是,当您在 UI 中更改路线时,角度会处理它。它访问 API 并为您提供应用程序期望的 json 响应。但是,当您在浏览器上刷新时,您的节点服务器会获取完整的 url localhost:3000/search 并返回 json 响应,而不是返回 HTML 或 js 文件,并且相同的 json 会显示在浏览器中。

【讨论】:

  • 感谢您的回复。我认为这就是正在发生的事情,但是我将如何更改路由以解决问题而不会导致 404?编辑:在上面添加我的 package.json。我的 npm start 创建代理并编译我的 Angular 应用程序。
  • 只需更改您的 Angular 应用程序调用的获取/发布 url。在应用程序和服务器中进行更改。
  • 很抱歉,您能否更具体地说明应该修改的内容?我添加了我的结果组件的 ngOnInit,其中调用了服务方法。我很好奇 Angular 是否因为查询参数而无法路由。
  • 更改服务器端的api以及角度的URL。在您的服务方法中,将 this.http.get(/homeaway/search, options) 替换为 this.http.get(/homeaway/search-something, options) 并在服务器端将 router.get('/search', (req,res,next) =&gt; { 替换为 router.get('/search-something', (req,res,next) =&gt; {
  • 它有效,谢谢!然后,我在更改并实施 HashLocationStrategy 后开始在页面刷新时出现 404,这解决了 404。感谢您的帮助
猜你喜欢
  • 2014-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多