当我们在浏览器地址栏进行域名访问时,默认只能向浏览器服务端发送GET请求
当我们需要发送POST请求时,我们可以通过控制台输入来实现
在浏览器页面按下F12,本文演示为访问本地后端运行的服务端
1.如果后端接口没有请求参数,则直接使用下面非常简单的代码^_^
同时将请求url换成自己的
fetch(new Request('http://localhost:8080/wz',{method:'POST'})).then((resp)=>{console.log(resp)})
2.后端接口使用 @RequestParam 来接收请求头中的参数
在控制台运行以下代码,将请求url和请求参数换成自己的
var url = "http://localhost:8080/portal/showHeadlineDetail?hid=1"; // 将 hid 作为查询参数
var xhr = new XMLHttpRequest();// 创建一个新的 XMLHttpRequest 对象,用于发送 HTTP 请求
xhr.open("POST", url, true);// 初始化请求,指定请求方法为 POST
// 定义请求的响应处理函数
xhr.onload = function (e) {
// 检查请求的状态是否完成
if (xhr.readyState === 4) {
// 当请求成功(HTTP 状态码为 200)时,打印响应内容
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
// 如果请求失败,打印错误状态
console.error(xhr.statusText);
}
}
};
// 定义网络错误处理函数
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(); // 不发送请求体
3.后端接口使用 @RequestBody来接收请求头中的参数
//定义请求头
var url = "http://localhost:8080/user/login";
//定义请求体
var params = {
"username":"lisi",
"userPwd":"123456"
};
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
// 设置请求头,指定内容类型为 JSON
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
// 发送请求,将参数对象转换为 JSON 字符串作为请求体
xhr.send(JSON.stringify(params)); // 发送 JSON 请求体