使用express.js的时候遇到了跨域问题
解决方法有两种
1.手动解决
app.all('*',function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods","PUT,GET,POST,DELETE,OPTIONS");
res.header("Access-Control-Allow-Headers","X-Requestd-With");
res.header("Access-Control-Allow-Headers","Content-Type");
next()
});
此方法需要前端请求和后端请求的请求头一致。
2.引用用cors包 、
//跨域包
const cors=require('cors')
// 跨域包引用
app.use(cors())
此方法会自动给你添加你需要的请求头。
前端json传参问题
在我使用ajax封装的函数中需要请求post类型的接口时候,遇到了数据传不到后端问题
之后发现是需要带请求头
xhr.open(method,'http://localhost:3001/api'+url,true)
//请求头带json数据
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
if(data!=''){
console.log(data);
xhr.send(JSON.stringify(data))
}else{
xhr.send()
}
请求头的方法汇总
XHR发送数据后端接收不到
- post请求,通过XMLHttpRequest.setRequestHeader()设置请求头,服务器通过Content-Type,得到请求数据的类型,然后进行解析
- text/html : HTML格式
- text/plain : 纯文本格式
- application/json:
xhr.send(data) ,data是json格式{“a”:“b”}(需要序列化)xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); date = {"time1":time1, "time2":time2} xhr.send(JSON.stringify(date)); //post请求传的参数
- application/x-www-form-urlencoded:
xhr.send(data),data是键值对格式“a=b”xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send("time1="+time1+"&time2="+time2); //post请求传的参数
- multipart/form-data:
xhr.send(data),data是表单格式(多用于文件上传)