Angular 6 调用本地主机 API [英] Angular 6 call localhost API
问题描述
我试图在我的 angular 6 应用程序中本地调用 api,api url 是 http://localhost/myapi
我添加了一个指向这个 url 的代理配置文件,但我得到了404
运行我的应用程序时出错.
I am trying to call an api locally in my angular 6 app, the api url is http://localhost/myapi
I added a proxy config file that point to this url but I got
404
error when I run my app.
我的 proxy.config.json 文件:
My proxy.config.json file:
{
"/api/*":{
"target":"http://localhost/myapi",
"secure": false,
"logLevel": "debug"
}
}
package.json 文件:
package.json file:
"serve-dev": "ng serve --source-map=false --proxy-config proxy.config.json",
http.service.ts 文件:
http.service.ts file:
export class HttpService{
static serverApiUrl : string = "/api/"
}
auth.service.ts 文件:
auth.service.ts file :
this.http.get(HttpService.serverApiUrl+"site/check-auth")
.map(response => {
if(response['auth'] == 1) {
return true;
} else {
this.router.navigate(['/auth'])
return false;
}
});
在控制台中我得到了这个:
In the console I got this:
http://localhost:4200/api/site/check-auth
任何建议.
推荐答案
看起来你需要重写 URL 路径,使用如下所示:
It looks like you need to rewrite the URL path, using something like this:
{
"/api": {
"target": "http://localhost",
"secure": false,
"logLevel": "debug",
"pathRewrite": {
"^/api": "/myapi"
}
}
}
我已经从您拥有的前缀中删除了 /*
并添加了一个 pathRewrite
部分.我相信您之前尝试代理到 localhost/myapi/api/site/check-auth
(使用额外的 /api
),应该用pathRewrite
部分.
I've removed /*
from the prefix you had and added a pathRewrite
section. I believe what you had before was attempting to proxy to localhost/myapi/api/site/check-auth
(with that extra /api
), which should be stripped with the pathRewrite
section.
这篇关于Angular 6 调用本地主机 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!