let fd=new FormData();
fd.append('username',this.userName);
fd.append('password',this.userPwd);
fd.append('checkCode',this.code);
fetch(`${apiUrl}/login`,{
method:'post',
body:fd,
credentials: 'include'
}).then((res)=>res.json()).
then((res)=>{
console.log(res);
}).catch((res)=>console.log(res));
后台代码
(注:
response.setHeader("Access-Control-Allow-Origin", "http://192.168.1.136:8080";);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
response.setHeader("Access-Control-Allow-Credentials", "true");//是否支持cookie跨域
后台什么都不需要加,根本不需要加跨域这些东西)。
javascript 使用fetch进行跨域请求时默认是不带cookie的,所以会造成 session失效。
fetch(url, {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/x-www-form-urlencoded',
},
body: JSON.stringify({
data: options.data
})
})credentials: 'include' 可以是fetch 带上cookie。但是问题了来。
原来在服务器端设置header (php 服务器)
header("Access-Control-Allow-Origin: *");
会报错:
A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:8000' is therefore not allowed access.
可以看到不允许 使用‘*’ 号了,那么就改成 访问域名(这里是本地调用所以是 http://localhost:8000)
header("Access-Control-Allow-Origin: http://localhost:8000");
改完后再次发送请求,还是报错
Credentials flag is 'true', but the 'Access-Control-Allow-Credentials' header is ''. It must be 'true' to allow credentials. Origin 'http://localhost:8000' is therefore not allowed access.
说'Access-Control-Allow-Credentials 头必须是true,那么继续增加
header("Access-Control-Allow-Credentials: true");
增加完后可以正常访问了,而且session也有了。
ps: fetch 有个mode 是no-cors ,发现设置后返回的status是0,查资料后
no-cors
mode is only to CDN content, such as scripts, CSS and image, you cannot be used for getting data,response.status = 0
is right behavior
no-cors 模式只能用来获取CDN内容,比如脚本,css文件和图片,如果用来获取数据比如json格式就会返回status=0
终极方案(推荐使用):
既然fetch不会自动转FormData,那我们自己new一个FormData,直接传给body。
在FormData中也可以传递字节流实现上传图片的功能。参考:http://blog.csdn.net/codetomylaw/article/details/52446786
[javascript] view plain copy
let formData = new FormData();
formData.append("name","admin");
formData.append("password","admin123");
etch(url , {
method: 'POST',
headers: {},
body: formData,
).then((response) => {
if (response.ok) {
return response.json();
}
).then((json) => {
alert(JSON.stringify(json));
).catch((error) => {
console.error(error);
);
这样我们就可以在Server端获取到name和password的值了。