简单请求
- 请求方式是 get, post , head 之一
- http头部信息不超过以下几种:
- Accept
- Accept-language
- Content-language
- Last-Event-ID
- Content-Type: 只限于
application/x-www-form-urlencoded
,mutipart/form-data
,text/painn
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/test', true); // 异步提交
xhr.setRequestHeader('Content-Type', 'application/json'); // 自定义Content-Type
xhr.send(JSON.stringify({ name: 'zwh' }))
xhr.responseType = 'json'; // 浏览器把json字符串解析成对象
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.response);
}
};
// xhr.onload = function () { // xhr.readyState == 4 xhr.status == 200
// console.log(xhr.response)
// }
</script>
</body>
</html>
后台代码
const http = require('http');
const url = require('url');
let server = http.createServer((req, res) => {
let { pathname } = url.parse(req.url);
// 配置Header
res.setHeader('Access-Control-Allow-Origin', req.headers.origin); // 允许任何网站的访问
res.setHeader('Access-Control-Allow-Headers', 'Content-Type,Authorization'); // 允许请求携带的自定义头Content-Type 和 Authorization
res.setHeader('Access-Control-Allow-Methods', 'GET,POST,PUT'); // 允许请求的方法。不设置就是默认支持的 get 和 post
res.setHeader("Access-Control-Max-Age", "1800"); // 表示隔30分钟才发起预检请求
// 如果是options请求,直接成功
if (req.method === 'OPTIONS') {
res.statusCode = 200;
res.end();
}
// 接收数据
const arr = [];
req.on('data', function (chunk) {
arr.push(chunk);
})
req.on('end', function () {
let result = Buffer.concat(arr).toString();
// result = querystring.parse(result, '&', '=');
if (pathname === '/test' && req.method == 'POST') {
res.end(result);
}
})
})
server.listen(3000);
转载
- 跨域和CORS配置 https://www.cnblogs.com/zhuwenhua/p/14052634.html