【发布时间】:2021-01-04 20:34:56
【问题描述】:
我尝试了很多东西,它只会在它有“mode: no-cors”并且没有标题时才发布到 api。
我现在正在尝试使用 mode: 'cors',因为我读到出于安全原因我不应该使用 'no-cors'。但是,我必须删除标题,否则它不会发布数据。
代码如下:
signUp: async(email, password)=> {
let values = {
firstname: "pruebaNombre",
lastname: "pruebaApellido",
email: email,
password: password
}
const config = {
method: 'POST',
mode: 'cors',
// headers: {
// 'Access-Control-Allow-Origin':'*',
// 'Content-Type': 'application/json'
// },
body: JSON.stringify(values),
}
const response = await fetch('http://localhost/rest-api-authentication-example/API/create_user.php', config);
const data = await response.json();
console.log(data);
}
console.log(data) 应该是带有“用户已创建”消息的 json,但我收到以下错误:
CORS 策略已阻止从源“http://localhost:19006”获取“http://localhost/rest-api-authentication-example/API/create_user.php”的访问权限:“访问- Control-Allow-Origin 标头的值 'http://localhost/rest-api-authentication-example/' 不等于提供的来源。让服务器发送带有有效值的标头,或者,如果不透明的响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用 CORS 的资源。
加载资源失败:net::ERR_FAILED
Uncaught (in promise) TypeError: Failed to fetch
数据确实发布在我的服务器上,但我无法从获取中获得响应。
已编辑。- 这些是我的服务器端的标头:
header("Access-Control-Allow-Origin: http://localhost/rest-api-authentication-example/");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
【问题讨论】:
-
您能否更新您的问题以将您的 CORS 配置包含在您的服务器中
-
@rantao 好的,我刚刚编辑了它
标签: javascript reactjs fetch