我是codeIgniter的新手,我使用代码点火器构建了一个REST Web服务。
使用react JS的UI。
在邮递员网络服务似乎工作正常。但是当我整合React JS时,它会抛出一个错误。
无法加载http://123.0.0.5:81/codeigniter-rest-api/index.php/auth/login:请求标头字段Access-Control-Allow-Origin在预检响应中不允许使用Access-Control-Allow-Origin。 EmployeeLogin.js:2未捕获(在承诺中)TypeError: 无法获取
我的网络服务是: 123.0.0.5:81/codeigniter-rest-api/index.php/auth/login
我的React服务器是: localhost / 3000
我搜索了解决方案,但我在控制器中尝试了但没有工作。
class Auth extends CI_Controller {
function __construct() {
parent::__construct();
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
}
我的反应消费脚本是:
(async () => {
const rawResponse = await fetch('http://123.0.0.5:81/codeigniter-rest-api/index.php/auth/login', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(datapost)
});
const content = await rawResponse.json();
alert(content);
})();
答案 0 :(得分:1)
更改:将fetch('http://...)
更改为fetch('https://...)
或fetch('//...)
。
您不能通过HTTP(仅HTTPS)执行CrossOrigin请求。