简体   繁体   中英

Javascript client get response from server

I fill in a form in html and then submit it. At first the client validates the data (eg if the eula checkbox is accepted) and after the client sends the data to the server. The server checks also the data returns a status code to me. How can I get this status code from the server?

Here are some example snippets

HTML

    <form name="newsletter" method="post" action="/api/newsletter" onsubmit="if(!validate()){return false;} else tryToFetch();"> 
    <input name="name" type="text" id="name"/>
    <input name="eula" type="checkbox" id="eula"/>
    <input  type="submit" name="submit"/> </form>

client js:

function validate() {
    if (this.eula.checked == false) { alert ('EULA NOT ACCEPTED'); return false; } else {
        return true; }
}

tryToFetch

function tryToFetch(){
    fetch('http://localhost:3000/api/newsletter')
        .then(function(response) {
            console.log(response.status ) ;
        });
}

Server.js

app.post('/api/newsletter', urlencodedParser ,function (request, response) {
//Just check some data...
    response.statusCode = 999;
    response.send('999');
});

Now how can I get the status code 999 in the browser and handle it? Is it even possible todo only using js?

As written in Fetch documentation :

"The fetch specification differs from jQuery.ajax() in two main ways:

The Promise returned from fetch()won't reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing."

So maybe this is causing your problem ? Have you tried using default XMLHttpRequest.

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