报错信息:Access to XMLHttpRequest at 'http://localhost:8081/' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
主要是在 服务端返回的响应中 添加下面的头信息,不能直接写在 res.writeHead()
中
//看实际需求 一般只加第一个就行了
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");//以及你自己需要的字段
res.setHeader("Access-Control-Expose-Headers", "*");
完整代码如下:
服务端 node.js 代码
代码语言:javascript复制var http = require('http')
var url = require("url");
var fs = require('fs')
http.createServer(function(req, res) {
//主要时添加下面的几个配置就行
//直接写在 res.writeHead() 中没用
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");
res.setHeader("Access-Control-Expose-Headers", "*");
res.writeHead(200, 'Content-Type', 'application/json;charset=utf-8');
//获取get请求后面带的参数
var params = url.parse(req.url, true).query;
if (params && params.name && params.url) {
res.write("网站名:" params.name);
res.write("n");
res.write("网站url = " params.url);
res.end();
} else {
fs.readFile('../resource/demo.txt', function(err, data) {
if (err) return res.end();
res.write(data);
res.end();
})
}
}).listen(8081);
前端Vue代码
代码语言:javascript复制<head>
...
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="vue_ajax">
<p>{{info}}</p>
</div>
<script type="text/javascript">
var vm = new Vue({
el: "#vue_ajax",
data: {
info: null,
},
mounted() {
axios
.get('http://localhost:8081/')
.then(res => (this.info = res))
.catch(function(err) {
console.log(err)
});
}
});
</script>
</body>
</html>