简体   繁体   English

通过 javascript 向 REST API 发送 POST 请求

[英]Send POST request to REST API via javascript

First, I read somewhere that we should not use XMLHttpRequest .首先,我在某处读到我们不应该使用XMLHttpRequest

Second, I am a newbie in Javascript.其次,我是 Javascript 的新手。

Third, I created a webpage to submit email and password.第三,我创建了一个网页来提交电子邮件和密码。

<form method="POST" onsubmit="return check();">{% csrf_token %}
    <p><b>Login</b></p>
    <input type="email" name="email" placeholder="Email" required></input>
    <input type="password" name="password" placeholder="Password" id='new_password' ></input>
    <span id='message'>{{msg}}</span>
    <button type="submit" onclick="check()" name="Submit"><b>Submit</b></button>
</form>

My check function is我的检查功能是

function check() {        
    document.getElementById('message').innerHTML = "checking";
    const url = "https://<hostname/login";
    const data = {
        'email' : document.getElementById('email').value,
        'password' : document.getElementById('password').value
    };

    const other_params = {
        headers : { "content-type" : "application/json; charset=UTF-8" },
        body : data,
        method : "POST",
        mode : "cors"
    };

    fetch(url, other_params)
        .then(function(response) {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error("Could not reach the API: " + response.statusText);
            }
        }).then(function(data) {
            document.getElementById("message").innerHTML = data.encoded;
        }).catch(function(error) {
            document.getElementById("message").innerHTML = error.message;
        });
    return true;
}

This code is not working and just redirects me to the same page again and again.此代码不起作用,只是一次又一次地将我重定向到同一页面。

Please help me understand what am I doing wrong.请帮助我了解我做错了什么。

The problem with your code is that you are not "intercepting" the submit event of your form so it will execute the default behavior which is POST to itself (since it doesn't have an instruction that tells it where to go).您的代码的问题在于您没有“拦截”表单的提交事件,因此它将执行默认行为,即POST到自身(因为它没有告诉它去哪里的指令)。 Unless you can have a chance to stop this default behavior, the form will perform this action.除非您有机会停止此默认行为,否则表单将执行此操作。

To intercept the form's submit event you have to tell the browser to watch out of this event and execute a custom function instead of using an event listener like below:要拦截表单的提交事件,您必须告诉浏览器注意此事件并执行自定义函数,而不是使用如下所示的事件侦听器:

<script>

document.getElementById('whatever-form-id')
  .addEventListener('submit', check);

function check(e) {
  e.preventDefault();
  // and now anything else you want to do.
}

</script>

This will prevent your form from posting and it will execute your function instead.这将阻止您的表单发布,而是执行您的功能。

1) Your validation function always returns true 1) 你的验证函数总是返回true
2) When you use fetch..then , its promises can be executed later than return statement 2) 当你使用fetch..then ,它的 promises 可以在 return 语句之后执行

So your form will be refresh again and again.所以你的表单会一次又一次地刷新。 You should return false, and manually submit the form with JavaScript when you get an onSuccess response.您应该返回 false,并在收到onSuccess响应时使用 JavaScript 手动提交表单。

<script>
    function check(event) {
        document.getElementById('message').innerHTML = "checking";

        const url = "https://localhost:8080/login";
        const data = {
            'email' : document.getElementById('email').value,
            'password' : document.getElementById('new_password').value
        };
        const other_params = {
            headers : { "content-type" : "application/json; charset=UTF-8" },
            body : data,
            method : "POST",
            mode : "cors"
        };

        fetch(url, other_params)
            .then(function(response) {
                if (response.ok) {
                    alert(response.json());
                } else {
                    throw new Error("Could not reach the API: " + response.statusText);
                }
            }).then(function(data) {
                document.getElementById("message").innerHTML = data.encoded;
            }).catch(function(error) {
                document.getElementById("message").innerHTML = error.message;
            });
        return false;
    }
</script>

<form method="POST" onsubmit="return check();">{% csrf_token %}
    <p><b>Login</b></p>
    <input type="email" id = "email" name="email" placeholder="Email" required></input>
    <input type="password" name="password" placeholder="Password" id='new_password' ></input>
    <span id='message'>{{msg}}</span>
    <button type="submit" name="Submit"><b>Submit</b></button>
</form>

Update:更新:

Page not refreshed, error message displayed:页面未刷新,显示错误消息: 在此处输入图片说明

There were some errors in your code as I've checked, please use it like this我检查过你的代码中有一些错误,请像这样使用它

<form method="POST" onsubmit="return check();">{% csrf_token %}
    <p><b>Login</b></p>
    <input type="email" id = "email" name="email" placeholder="Email" required>   
    <input type="password" name="password" placeholder="Password" id='new_password' >
    <span id='message'>{{msg}}</span>
    <button type="submit" onclick="check(event)" name="Submit"><b>Submit</b>  </button>
</form>
<script>
    function check(event) {
        event.preventDefault();
        document.getElementById('message').innerHTML = "checking";

        const url = "https://hostname/login";
        const data = {"email" : document.getElementById('email').value,
                    'password' : document.getElementById('new_password').value
                    };
        const other_params = {
            headers : { "content-type" : "application/json; charset=UTF-8"},
            body : data,
            method : "POST",
            mode : "cors"
        };

        fetch(url, other_params)
            .then(function(response) {
            if (response.ok) {
                return response.json();
            } else {
                throw new Error("Could not reach the API: " + response.statusText);
            }
        }).then(function(data) {
            document.getElementById("message").innerHTML = data.encoded;
        }).catch(function(error) {
            document.getElementById("message").innerHTML = error.message;
        });
        return true;
    }
  </script>

Then test by changing your post URL to correct one whether working or not, for more testing use browser inspector tool to see your ajax request.然后通过更改您的帖子 URL 以更正一个是否有效进行测试,更多测试使用浏览器检查器工具来查看您的 ajax 请求。

I've also put it on fiddle for your live testing http://jsfiddle.net/rajender07/xpvt214o/903616/我也把它放在小提琴上用于你的现场测试http://jsfiddle.net/rajender07/xpvt214o/903616/

Thanks谢谢

Firstly, I would like to understand what is your object after getting the data from REST API.首先,我想了解从 REST API 获取数据后您的对象是什么。

Secondly, there are mistakes in the html code as well, you don't need to add onclick on the submit button when there you already have a onsubmit on the form element.其次,html代码中也有错误,当你已经在表单元素上有一个onsubmit时,你不需要在提交按钮上添加onclick

Solution, change onsubmit="check(event);"解决办法,改onsubmit="check(event);"

function check(e) { e.preventDefault() ... } // you can remove the return true

just going off the top of my head here but you've set the Content-Type to application/json in the headers but your body is not an JSON string刚刚在这里离开我的头顶,但您已将标题中的Content-Type设置为application/json但您的正文不是 JSON 字符串

try making your body match the headers by doing尝试通过执行使您的身体与标题匹配

const other_params = {
  headers : { "content-type" : "application/json; charset=UTF-8"},
  body : JSON.stringify(data),
  method : "POST",
  mode : "cors"
};

EDIT编辑

So after re-reading your question, I think what is happening is you've set your button to type of submit and what is happening is when you click on the button, your form is getting posted through the good old form post and your page gets refreshed from the postback.因此,在重新阅读您的问题后,我认为发生的事情是您已将button设置为submit类型,而当您单击按钮时,您的表单将通过旧的表单帖子和您的页面发布从回发中得到刷新。

If you want to handle form posts yourself using fetch, change your button type to button and the form should no longer actually post then everything else will be handled by your click event handler.如果您想使用 fetch 自己处理表单帖子,请将您的按钮类型更改为button并且表单不应再实际发布,那么其他所有内容都将由您的点击事件处理程序处理。

ps.附: while you're at it, you can remove the method and onsubmit attribute from your form tag as well当您使用它时,您也可以从表单标记中删除methodonsubmit属性

So your form should look something like this所以你的表格应该是这样的

<form>
    <p><b>Login</b></p>
    <input type="email" name="email" placeholder="Email" required></input>
    <input type="password" name="password" placeholder="Password" id='new_password' ></input>
    <span id='message'>{{msg}}</span>
    <button type="button" onclick="check()" name="Submit"><b>Submit</b></button>
</form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM