简体   繁体   中英

How to get request url in an angularjs $http request

I have this request:

$http({
  method: 'get',
  url: '/api/items/',
  params: {a: 1, b: 2, c: 3}
}).success(function (response) {
  console.log(response);
}).error(function (err) {
  console.log(err);
});

Is there a way, to fetch the url it used to make the request after the request has been made(in the callback or otherwise)?

I would want the output:

http://www.example.org/api/items?a=1&b=2&c=3

Here the same thing is done with jquery.

The success handler gets 4 parameters passed into it:

$http
  .get({ url: '/someUrl', params: { q: 3 } })
  .success(function(data, status, headers, config) {});

The fourth parameter config has the following properties:

{
  method: "GET",
  url: {
    url: '/someUrl',
    params: {
      q: 3
    }
  }
}

You can use window.location.origin to get the base url and build a simple function to concat it all together.

This function should yield the expected response:

var baseUrl = window.location.origin;
var query = [];
Object.keys(config.url.params || {}).forEach(function (key) {
  var val = config.url.params[key];
  query.push([key, val].join('=')); // maybe url encode
});
var queryStr = query.join('&');
var fullPath = baseUrl + config.url.url + '?' + queryStr;

Unfortunately, this function will only work as long as the parameters are passed in the format described above. If you pass them in a different format, you'll have to modify this function a bit. You can use this as a playground .

Afaik, there is no simpler way. At least a feature request exists .

See the docs of $http for reference

This config parameter of the callback has the url as a property:

// Simple GET request example :
$http.get('/someUrl').
  success(function(data, status, headers, config) {
    console.log(config.url);
  }).
  error(function(data, status, headers, config) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Based on: https://docs.angularjs.org/api/ng/service/ $http

You can use http request Interceptor. Configure the Interceptor in config function using $httpProvider Whrein for request Interceptor you can able to see the URL and params that you passed with URL prior to making the request

尝试在浏览器开发工具中查看XHR请求网址

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM