使用fetch跨域POST请求

解决跨域问题

加入跨域用的响应头:

“Access-Control-Allow-Origin” : “*”,
“Access-Control-Allow-Credentials” : true

fetch()发送请求的代码如下:

fetch("localhost:8080/getAll", {
    method: 'post', // 如果是get方式的话,只能把参数拼接在url里传过去,get方式不能有body
    "Access-Control-Allow-Origin" : "*",
    "Access-Control-Allow-Credentials" : true,
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(this.state) // 把你要传的数据放在这里转化成json
}).then(function (response) { // 处理返回回来的数据
    return response.json();
}).then(function (respsoneData) {
    let jsonData = jQuery.type(respsoneData) == 'string' ? JSON.parse(respsoneData) : respsoneData;
    console.log("得到了所有的对象:");
    console.dir(jsonData);
});


评论