Fetch
fetch是用来取代传统的XMLHttpRequest的。 它的优点很多,包括链式调用的语法、返回promise等。
fetch api是基于promise的设计,它是为了取代传统xhr的不合理的写法而生的。
传统ajax
xhr请求写起来非常的混乱,如下所示
1 | var xhr = new XMLHttpRequest(); |
但是使用fetch之后,如下所示:
1 | fetch(url).then(function(response) { |
这种链式调用的风格看上去会非常舒服。
如果我们再使用了箭头函数就会更加简洁了。
1 | fetch(url).then(response => response.json()) |
Access-Control-Allow-Origin”, “*” //所有的网站
Access-Control-Allow-Headers”, “Content-Type,Content-Length, Authorization, Accept,X-Requested-With”
Access-Control-Allow-Methods”,”PUT,POST,GET,DELETE,OPTIONS” //Restful请求规范 支持符合Restful的所有协议
1 |
1 |
|
var express =require(‘express’);
var app=new express();
var request=require(‘request’);
//1 CORS跨域
app.use(function (req,res,next) {
//每一次发送的请求头
//支持cors跨域
res.header(‘Access-Control-Allow-Origin’,’*’);
next();
});
app.get(‘/getdata’,function (req,res) {
res.send(‘{“text”:”CORS跨域”}’);
});
//2 jsonp跨域
app.get(‘/getjsonp’,function (req,res) {
console.log(req.query.callback);
console.log(req.querystring);
res.send(;${req.query.callback}({"text":"CORS跨域"});
);
});
//3 服务器转发跨域
app.get(‘/request’,function (req,res) {
var url=’https://api.douban.com/v2/book/1220562'
request(url,function (error,response,body) {
console.log(body);
if(!error){
res.send(body);
}
})
});
app.listen(‘3001’,function(){
console.log(‘端口3001被打开了’);
});`