参考文档:https://www.freecodecamp.org/chinese/news/the-most-popular-ways-to-make-an-http-request-in-javascript/

1.form表单提交

<form action="http://www.baidu.com" method="post">
    <input type="text" name="name" value="123">
    <input type="submit" value="提交">
</form>

只能单向提交,不能接收返回值。

2. XMLHttpRequest

var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); // 设置请求头
xhr.send(JSON.stringify({name: '123'})); // 发送请求,body。如果后端不接受body类型的请求,则直接将参数放在url中,这里只需写成xhr.send()即可
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        console.log(xhr.responseText);
    }
}

注意setRequestHeader必须在open之后,send之前设置,如果放在open之前则会报以下错:

Uncaught DOMException: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.

3. fetch

fetch需要es6的支持,nodejs需要v17.5.0以上版本

fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    body: JSON.stringify({name: '123'})
}).then(res => res.text()).then(res => console.log(res));