nodejs端
const cors = require('cors');
var app=express();
var corsOptions = {
origin: 'http://localhost:8080',
credentials: true,
maxAge: '1728000'
//这一项是为了跨域专门设置的
}
app.use(cors(corsOptions))
前端
1.vue-resource
this.$http.get('getlogin',{ credentials: true }).then(res => {
console.log(res)
})
this.$http.post('postlogin',{userInfo: $('.form-signin').serialize()},{ credentials: true }).then(res => {
console.log(res)
if(res.body.status != 200) {
console.log('登录失败')
}else {
console.log('登录成功')
}
})
2.原生js中api
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.xxx.com/api');
xhr.withCredentials = true;
xhr.onload = onLoadHandler;
xhr.send()
3.jquery中
$.ajax({
url: "http://localhost:8080/orders",
type: "GET",
xhrFields: {
withCredentials: true
},
crossDomain: true,
success: function (data) {
render(data);
}
});
4.axios
const service = axios.create({
baseURL: process.env.BASE_API, // node环境的不同,对应不同的baseURL
timeout: 5000, // 请求的超时时间
//设置默认请求头,使post请求发送的是formdata格式数据// axios的header默认的Content-Type好像是'application/json;charset=UTF-8',我的项目都是用json格式传输,如果需要更改的话,可以用这种方式修改
// headers: {
// "Content-Type": "application/x-www-form-urlencoded"
// },
withCredentials: true // 允许携带cookie
})
https://www.cnblogs.com/lijinwen/p/8012547.html