gpt4 book ai didi

AngularJS全局修改$http中每个请求的URL

转载 作者:行者123 更新时间:2023-12-02 19:23:47 24 4
gpt4 key购买 nike

让我们设置一个简单的示例:

$scope.whatDoesTheFoxSay = function(){
$http.post("/backend/ancientMystery", {
...

如何全局转换 post 请求发送到的 URL?本质上我想在每个 http 请求前面添加一个 URL。

我尝试的是在应用程序启动时在包含 url 的 $rootScope 中设置一个变量。但这不是我想要的代码:

$scope.whatDoesTheFoxSay = function(){
$http.post($rootScope.backendUrl + "/backend/hidingDeepInTheWoods", {
...

我是否正确假设我应该研究$httpProvider.defaults.transformRequest?谁能给我提供一些基本的示例代码?

最佳答案

我有另一种方法,将请求拦截器与 $http 一起使用,它将在一个公共(public)位置处理所有 url

<!doctype html>
<html ng-app="test">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.2/angular.js"></script>

</head>
<body ng-controller="test" >


<!-- tabs -->


<script>
var app = angular.module('test', []);
app.config(function ($httpProvider) {
$httpProvider.interceptors.push(function ($q) {
return {
'request': function (config) {
config.url = config.url + '?id=123';
return config || $q.when(config);

}

}
});
});

app.controller('test', function ($scope,$http) {
$http.get('Response.txt').success(function (data) { alert(data) }).error(function (fail) {

});
});

</script>
</body>


</html>

关于AngularJS全局修改$http中每个请求的URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18984518/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com