Fetch API 发送 POST 和 GET 请求(含跨域)
概述
Fetch API 是现代浏览器内置的 HTTP 请求方法,替代了老旧的 XMLHttpRequest。支持 Promise 和 async/await,语法更简洁。本文涵盖 POST、GET 请求和跨域配置。
POST 请求
var data = {"code": 0, "msg": "你好"};
fetch("http://localhost:55087/Forguncy/ServerCommand/data", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => console.log(data))
.catch(err => console.error("请求失败:", err));GET 请求
fetch("http://localhost:55087/Forguncy/ServerCommand/data")
.then(response => {
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
return response.text();
})
.then(data => console.log(data))
.catch(error => console.error(error));使用 async/await(推荐)
async function sendRequest() {
try {
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
});
if (!response.ok) {
throw new Error("HTTP " + response.status);
}
const result = await response.json();
console.log(result);
return result;
} catch (error) {
console.error("请求失败:", error);
throw error;
}
}跨域说明
如果服务端响应头中包含 CORS 头(如 Access-Control-Allow-Origin),即可实现跨域请求。服务端配置示例:
// PHP 设置跨域头
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");响应处理方式
| 方法 | 返回值 | 适用场景 |
|---|---|---|
| response.json() | Promise → JSON 对象 | API 返回 JSON |
| response.text() | Promise → 字符串 | HTML/纯文本 |
| response.blob() | Promise → Blob | 文件/图片下载 |
| response.formData() | Promise → FormData | 表单数据 |
完整封装示例
// 封装可复用的请求函数
const http = {
get: (url) => fetch(url).then(r => r.json()),
post: (url, data) => fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(data)
}).then(r => r.json())
};
// 使用
http.post("/api/save", { name: "test" })
.then(data => console.log(data));注意事项
- POST 请求需手动设置
Content-Type response.json()返回 Promise,需要 await 或 .then()- Fetch 默认不携带 Cookie,需设置
credentials: "include" - 只有网络错误才会进 catch,HTTP 错误(如 404)不会 reject,需手动检查
response.ok
暂无评论
快来发表第一条评论吧!