- 1、发送GET请求
- 2、发送POST请求
- 3、发送PUT请求
- 4、发送Delete请求
- node开启的服务支持跨域">5、node开启的服务支持跨域
1、发送GET请求
如果你有自定义的需求,可以访问官网:
let http = require('http');
// 格式化返回的参数 对json格式的数据进行格式化
function formatResData(data, headers) {
let type = headers['content-type'];
if (!type || type && type.indexOf('application/json') !== -1) {
if (typeof data === 'string') {
try {
data = JSON.parse(data);
} catch (e) { /* Ignore */ }
}
}
return data;
}
// 封装get请求
function get(url, headers = {}) {
return new Promise((resolve, reject) => {
const options = {
headers: headers
};
const req = http.get(url, options, res => {
let had = false;
res.setEncoding('utf8');
// 监听返回的数据
res.on('data', (chunk) => {
had = true;
// 数据格式化
res.data = formatResData(chunk, res.headers);
resolve(res);
});
// 监听接口请求完成, 除非error,最终都会执行end;
res.on('end', () => {
if (had) return;
resolve(res);
});
});
req.on('error', e => {
reject(e);
});
}).catch(e => {
console.error('Request error: ' + url + ', Method:' + 'GET' + ',Error message:', e);
throw new Error(e ? e : 'Request error');
})
}
从服务器取出资源(一项或多项)
GET请求的数据会附在URL之后(就是把数据放置在HTTP协议头中),以?分割URL和传输数据,参数之间以&相连
如果要在query部分带参数 (包括PUT POST DELETE)
如:
http://www.helloworld.com/messages/topic3?/messages/topic3?cmd=event&uid=A15C2DB&img=1
均需要使用qs模块进行处理:
// 调用示例
let headers = {
Cookie: 'xxxxxx'
};
get('http:xxxxxx', headers).then(res => {
// res.statusCode为接口返回的状态码, res.data为接口返回的数据
console.log(res.statusCode, res.data);
});
2、发送POST请求
let http = require('http');
// 封装POST请求
function post(url, data, headers = {}) {
return new Promise(resolve => {
const options = {
method: 'POST',
headers: headers
};
const req = http.request(url, options, res => {
let had = false;
res.setEncoding('utf8');
res.on('data', (chunk) => {
had = true;
// 当接口返回的是json格式数据时可以使用JSON.parse
res.data = formatResData(chunk, res.headers);
resolve(res);
});
// 监听接口请求完成, 除非error,最终都会执行end;
res.on('end', () => {
if (had) return;
resolve(res);
});
});
req.on('error', e => {
reject(e);
});
// 写入请求的数据
data && req.write(data);
req.end();
}).catch(e => {
console.error('Request error: ' + url + ', Method:' + 'GET' + ',Error message:', e);
throw new Error(e ? e : 'Request error');
})
}
// 调用示例
let data = {
name: 'xxx'
}
// 发送form表单格式数据
data = qs.stringify(data);
// 设置请求头(Content-Type)为form表单格式
let headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Cookie': 'xxxxx'
};
post('http:xxx', data, headers).then(res => {
// res.statusCode为接口返回的状态码, res.data为接口返回的数据
console.log(res.statusCode, res.data);
})
3、发送PUT请求
在服务器更新资源(客户端提供改变后的完整资源)
var request = require("request");
var options = {
url: 'http://xxxxxxxx.s3.us-east-1.amazonaws.com' +s3_path,// ,
headers: {
host: 'jwlipirtest.s3.amazonaws.com',
'x-amz-content-sha256':'UNSIGNED-PAYLOAD',
'x-amz-date':date,
Authorization: result
},
body:bitmap
};
request.put(options, function(error, response, body) {
console.info('response:' + JSON.stringify(response));
console.info("statusCode:" + response.statusCode)
console.info('body: ' + body );
});
4、发送Delete请求
从服务器删除资源。
var request = require("request");
var options = {
url:'http://172.28.28.4:3017/files/testhttp',
headers:{
uid:"xxxxxxxx"
},
form:{
target:"/user/one"
}//req.body
};
request.del(options, function(err, response, body){
console.info(response.body);
});
5、node开启的服务支持跨域
如果你需要在请求头接受cookie和Token进行权限验证,'Access-Control-Allow-Headers'里面需要添加Set-Cookie和接受的请求头名称,例如下面的例子中Authorization为接受的请求头名称。
var app = express();
// 允许跨域
app.use((req, res, next) => {
res.set({
'Access-Control-Allow-Credentials': true, //允许后端发送cookie
'Access-Control-Allow-Origin': req.headers.origin || '*', //任意域名都可以访问,或者基于我请求头里面的域
'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type,Set-Cookie,Authorization', //设置请求头格式和类型
'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',//允许支持的请求方式
'Content-Type': 'application/json; charset=utf-8'//默认与允许的文本格式json和编码格式
})
req.method === 'OPTIONS' ? res.status(200).end() : next()
})