简体   繁体   中英

How to send post data and go to url with angularjs?

I have an application with angularjs 1.6 and Java 8. I want to send POST data to another application and go to the url that this application determine.

The domain is that my application send data of a citizen that want to take a turn of a service. The other application, take this data and show a view with a form with all fields autocompleted with the data i had send. I have to do like this, because the user asks for it.

I have tried several ways to do this, for example with xmlHttpRequest but when I sent the post, the user page is not redirected (despite receiving status 302).

A possible solution that I have tried

$http({
                method: "POST",
                headers: { 
                    ...some headers...
                },
                data : someData,
                url: someExternalUrl
            })
            .then(function(response, headers) {
                //catch the location header of response
                var externalUrl = headers("Location");
                $window.location.href = externalUrl;
            }, 
            function(response) {
                //if fail
            });

Another:

            var url = someUrl;
            var params = JSON.stringify(jsonObject);
            http.open('POST', url, true);

            //Send the proper header information along with the request
            //http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            //Some other headers

            http.onreadystatechange = function() {//Call a function when the state changes.
                if(http.readyState == 4 && http.status == 200) {
                    alert(http.responseText);
                }
            }
            http.send(params);

How can i do it?

Thanks!

302 will not redirect your browser if you're using xmlHttpRequest (or fetch). You need to retrieve the data and do a window.location = 'newUrlHere'; whenever your post call is done.

You can do it several ways, here are two of them:

  • Your POST method returns a 302, you look at the headers, get the url and set the window location;
  • Your POST method returns an object or string in the body that has the new location you need to go. Get that and do window.location = newLocation; and you're good to go.

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