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
针对付办理前后台sessionid同等问题往后又碰着 参数通报不到后台,末了这样办理:终极方案(推举利用):
既然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的值了。