在响应头里设置:
'Access-Control-Allow-Origin': '*'
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>cors</title>
</head>
<body>
<script>
// 请求地址
fetch('http://localhost:3000/api/data')
// 请求体解析
.then(res => res.json())
// 获得数据
.then(result => console.log(result))
</script>
</body>
</html>
server.js
const http = require('http');
const libUrl = require('url')
http.createServer((req, res) => {
const url = libUrl.parse(req.url, true);
if (url.pathname === '/favicon.ico') return;
if (url.pathname === '/api/data') {
res.writeHead(200, {
'Content-Type': 'Application/json',
// 设置允许所有端口访问
'Access-Control-Allow-Origin': '*'
});
let obj = {
name: '张三',
age: 20,
sex: '男'
};
res.write(JSON.stringify(obj));
}
res.end();
}).listen(3000)