简体   繁体   中英

URL in a request is changed before run

I have a problem when I try to run a http request where my NodeJS application for some odd reason decides to add my domain to the URL that I have set in my http request. How do I make sure this does not happen?

I tried searching for similar issues but found none. Might be that I am unsure of what to actually search for.

Here is what I want to have run:

$.ajax({
    url: 'xxx.xxx.xxx.xxx',
    type: 'PUT',
    headers: {
        'value': 'value',
        'value2': 'value2' 
    },
    success: function(result) {
        // extra code...
    }
});    

And this is what happens in the request, as seen from console:

$.ajax({
    url: 'http://localhost:8080/xxx.xxx.xxx.xxx', // (added localhost)
    type: 'PUT',
    headers: {
       'value': 'value',
       'value2': 'value2' 
    },
    success: function(result) {
        // extra code...
    }
});

Worth noting (maybe) is that if I add http:// to my request URL it does not change when run, but that URL is not accepted. This request is to be run on the client side of things, ie in the browser.

That is the difference between absolute url and relative url. A url without its protocol is considered a relative url and so the following will happen.

Relative URL: user/1

Current Location: http://google.com/products

Result: http://google.com/products/user/1

or

Relative URL: /user/1

Current Location: http://google.com/products

Result: http://google.com/user/1

You URL is not quite a valid URL because it is missing a scheme and possibly other bits as well, so ajax is taking a best guess at what you meant.

The default for ajax() is to query the current page, which is http://localhost:8080 , and it took what you supplied as being a path on that page.

Try this instead:

url: ' http://xxx.xxx.xxx.xxx ',

if xxx.xxx.xxx.xxx is an url to another website, you'll have to specify the protocol or xxx.xxx.xxx.xxx will be interpretted as relative path.

In general this applies to src attributes as well (for img , srcipt and iframe ...). Any links in the page will be regarded as relative paths unless their protocol is specified.

For example: (just for explanation) on Windows if you have a path like some\\thing , it will be relative to wherever you are trying to access it (the absolute path of where you are trying to access it will be automatically prepended to the path some\\thing ). But if your path is C:\\some\\thing , then it will be always the same wherever it is accessed. The protocols works in similar ways.

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