问题
I have a vue app that sits behind a firewall, which controls user authentication. The only way that I have of detecting when the user needs to re-authenticate is when the axios requests sent by my app receive a 403 error. When this happens the server also returns a web page, which I see as, error.response.data. This page asks the user to re-authenticate via an embedded form that, when completed, authenticates the user and sends back the output from my app's original request.
My questions is how can I get the user to re-authenticate and then capture the data from my request that is returned? I can send the user the authentication page, for example by using:
var login_window = window.open('about:blank', '_blank');
login_window.document.write(error.response.data)
login_window.focus()
but then I don't see how to determine when the user has authenticated. When this happens, login_window.document.body.innerText contains the json data from my app's request, which my apps needs but which I don't want to show to the user. When doing this "by hand", I also have not succeeded in extracting the json from login_window.document.body.innerText as the json structure has been stripped and it now looks something like this:
JSON
Raw Data
Headers
Save
Copy
Collapse All
Expand All
status \"OK\"
message \"\"
user \"andrew\"
This question tries to reduce my previous question down to a javascript problem. There may be a better way to do what I want using axios; see Handling an authentication page returned by an axios request in vue for more details.
回答1:
One solution is to override the <form>'s submit-event handler, and then use XMLHttpRequest to submit the form, which gives you access to the form's response data and status code. A status code of 200 implies that the user is authenticated, and the response data should contain the response of the original request before authentication.
Steps:
Query the form's container for the
<form>element:const form = document.querySelector('#container > form').querySelector('form')Add a
submit-event handler that calls Event.preventDefault() to stop the submission:form.addEventListener('submit', e => { e.preventDefault() })Use XHR to send the original request, adding your own response handler to get the resulting data:
form.addEventListener('submit', e => { e.preventDefault() const xhr = new XMLHttpRequest() xhr.addEventListener('load', e => { const { response } = e.target const data = JSON.parse(response) // data now contains the response of the original request before authentication }) xhr.open(form.method, form.action) xhr.send(new FormData(form)) })
demo
来源:https://stackoverflow.com/questions/60347325/detect-form-submission-on-a-page