Fetch 跨域求情失败?

前端地址 localhost:8080
接口地址:http://www.haoyinguoji.com/ph...

图片描述
没有得到值
图片描述

import {
    baseUrl
} from './env'

export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
    type = type.toUpperCase();
    url = baseUrl + url;

    if (type == 'GET') {
        debugger;
        let dataStr = ''; //数据拼接字符串
        Object.keys(data).forEach(key => {
            dataStr += key + '=' + data[key] + '&';
        })

        if (dataStr !== '') {
            dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
            url = url + '?' + dataStr;
        }
    }

    if (window.fetch && method == 'fetch') {
        let requestConfig = {
            credentials: 'include',
            method: type,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            mode: "no-cors",
            cache: "force-cache"
        }

        if (type == 'POST') {
            Object.defineProperty(requestConfig, 'body', {
                value: JSON.stringify(data)
            })
        }

        debugger;

        try {
            const response = await fetch(url, requestConfig);
            const responseJson = await response.json();
            return responseJson
        } catch (error) {
            throw new Error(error)
        }
    } else {
        return new Promise((resolve, reject) => {
            let requestObj;
            if (window.XMLHttpRequest) {
                requestObj = new XMLHttpRequest();
            } else {
                requestObj = new ActiveXObject;
            }

            let sendData = '';
            if (type == 'POST') {
                sendData = JSON.stringify(data);
            }

            requestObj.open(type, url, true);
            requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            requestObj.send(sendData);

            requestObj.onreadystatechange = () => {
                if (requestObj.readyState == 4) {
                    if (requestObj.status == 200) {
                        let obj = requestObj.response
                        if (typeof obj !== 'object') {
                            obj = JSON.parse(obj);
                        }
                        resolve(obj)
                    } else {
                        reject(requestObj)
                    }
                }
            }
        })
    }
}
    export const accountLogin = (phone_num, user_pwd) => fetch('http://www.haoyinguoji.com/php/user.php?act=login', {
        phone_num,
        user_pwd
    },'POST');

php后台活得的参数,我不知道是我这里改还是后台啊~

array(1) {
  ["act"]=>
  string(5) "login"
}
阅读 1.3k
评论
    2 个回答

    服务端加上一个允许跨域的响应头就好了

      这种情况是因为对方的服务器只允许特定的域名请求,如果这是你自己的服务器,最简单的方法是服务端将响就头设置成 Access-Control-Allow-Origin:域名 如果不是你的服务器,可以考虑自己写一个服务器做中转,转发一下你的请求就可以了

        撰写回答

        登录后参与交流、获取后续更新提醒

        相似问题
        推荐文章