我的 Web 服务器位于 http://localhost:3000
,但我的 API 服务器位于 http://localhost:3001
。因此,不要像这样对我的所有请求进行开头:
var root = 'http://localhost:3001';
$http.get(root+'/')...
...如何将 http://localhost:3001
设置为所有传出 $http
请求的默认值?我试着看 Default Transformations , 但听不懂。
编辑:在更仔细地阅读了文档之后,我不太相信(但仍然不确定)Angular 有办法处理这个问题。看来您可以操纵 header 和数据,但不能操纵 url。
编辑 2:两个回答者建议使用全局函数/变量。这可行,但会导致 CORS 错误。
最佳答案
取决于您是从一个 js 文件还是跨多个 js 文件执行请求
//Create 2 global variables first outside the function then just use the
// var name when needed
var web = "http://localhost:3001";
var api = "http://localhost:3000";
或者,如果您需要跨多个 js 文件执行请求,您可以创建函数来返回每个 var,然后在需要时调用它们。请记住,需要先加载带有函数的文件。
function web() {
return "http://localhost:3001";
}
function api() {
return "http://localhost:3000";
}
那么就是
$http.get(api + '/')...
或
$http.get(api() + '/')...
编辑:更新您的其他问题
您的浏览器正在使用 OPTIONS 请求对 POST 请求进行预检,如果未获得批准,则不会向服务器发送真正的请求,这是预期的 COR 行为,在 COR 文档中有更多详细信息。
有几种方法可以解决这个问题,但一种常见的方法是在您的请求中添加 header :
var url = 'http://localhost:3001/users',
user= { 'someKey': 'some value' },
config = {
headers: {
'Content-Type': 'text/plain'
}
}
};
$http.post(url,user,config);
关于javascript - 如何在所有 $http 请求前加上 http ://localhost:3001?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31778096/