项目迁移vue,使用了vue推荐的axios请求方式。测试axios、ajax的异同
- html页面 - 引入jquery和ajax
- 分别模拟了ajax/axios的get/post请求方式
<body>
<button onclick="axiosFn()">axios</button>
<button onclick="ajaxFn()">ajax</button>
<button onclick="axiosPost()">axios-post</button>
<button onclick="ajaxPost()">ajax-post</button>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
<script>
var axiosFn = function (params) {
axios({
method: 'get',
url: 'http://127.0.0.1:8888/get?name=axios',
}).then(function (response) {
console.log(response);
}).catch(function (err) {
console.log(err);
});
}
var ajaxFn = function () {
$.ajax({
method: 'get',
url: 'http://127.0.0.1:8888/get?name=ajax',
success: function (data) {
console.log(data);
},
erroe: function (data) {
console.log(data);
}
})
}
var axiosPost = function () {
axios({
method: 'post',
url: 'http://127.0.0.1:8889',
data: {
name: "axios postMsg"
}
}).then(function (response) {
console.log(response);
}).catch(function (err) {
console.log(err);
});
}
var ajaxPost = function () {
$.ajax({
method: 'post',
url: 'http://127.0.0.1:8889',
data: {
name: "ajax postMsg"
},
success: function (data) {
console.log(data);
},
erroe: function (data) {
console.log(data);
}
})
}
</script>
</body>
- node 服务器端 get方法解析
var http = require("http");
var url = require("url");
var app = http.createServer(function (request, response) {
response.setHeader('Access-Control-Allow-Origin', 'null');
// response.writeHeader(200, {
// 'content-type': 'text/html;charset="utf-8"'
// });
// 接受请求的url
var url_json = url.parse(request.url);
var url_str = JSON.stringify(url_json);
if (url_json.path !== "/favicon.ico") {
response.write(url_str);
console.log(url_json.path);
}
response.end("hello world\n");
}).listen(8888, function () {
console.log('Server running at http://127.0.0.1:8888/');
});
- node 服务器端 post方法解析
var http = require("http");
var querystring = require("querystring");
var app = http.createServer(function (request, response) {
response.setHeader('Access-Control-Allow-Origin', 'null');
var postData = "";
request.on('data', function (chunk) {
postData += chunk;
});
request.on("end", function () {
// 解析参数
postData = querystring.parse(postData);
console.log(postData);
});
response.end("hello world\n");
}).listen(8889, function () {
console.log('Server running at http://127.0.0.1:8889/');
});
总结
-
例中跨域问题是因为html页面没有在服务器中运行,所以’Access-Control-Allow-Origin’, ‘null’
关于跨域参考
https://blog.csdn.net/flower46273736/article/details/62889077 -
axios post 请求的时候推荐使用qs查询字符串解析和字符串化库,增加了一些安全性。
https://www.npmjs.com/package/qs -
Axios/Ajax本质上都是对原生XHR的封装,只不过Axios是Promise的实现版本,符合最新的ES规范。
axios官网
https://www.kancloud.cn/yunye/axios/234845