【发布时间】: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