AngularJS $ http POST with port number

Is it possible to make an HTTP request using the port number in the url?

This is normal

$http.post('http://localhost/httpPost.json', data); 

But it does not work

  $http.post('http://localhost:8081/httpPost.json', data); 
+4
source share
3 answers

Yes, you can use the port number in your AngularJS request. So there are no problems here.

Could you be more precise in that "not working"?

Check your browser's console (F12 in Chrome, and also F12 if Firebug is installed in Firefox). This console probably displays an error message.

I suspect the Cross-Origin policy does not allow you to receive httpPost.json. This will happen if the call is not made from the place where you are trying to extract data (for example, if you opened the browser from a file system or from a server other than the one that runs on 8081)

+5
source

AngularJS Docs for $ resource say that "if you use a URL with a port number ... it will be respected." But this statement is valid only after version 1.2.0rc1, which is a completely new version with a violation of changes (source) .

There are several ways about this error:

 // named parameter $resource('http://example.com:8081', { '8081': ':8081' }); // named parameter $resource("http://example.com:port", { port: ':8081' }); // escaped $resource('http://example.com:8081\:8081'); 

Choose your poison. But if you cannot change every resource URL in your code, then there is another way. You can fix the error yourself by changing the line of code in angular -resource.min. I describe the process in the Google Group column that I inserted below:

Download angular-resource.js and edit it like this. According to the patch, you should replace line 348 with the following:

  if (!(new RegExp("^\\d+$").test(param)) && param && (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) { 

What is it. Just host the file on your own web server and you can enjoy the functionality as if it had never been broken. eight -)

+3
source

If your script is not served from the same port, the browser will not allow it. This is a safety measure. See CORS for more details.

+2
source

Source: https://habr.com/ru/post/1498158/


All Articles