Tôi đang làm việc trên ứng dụng React và tôi đang sử dụng tìm nạp để gửi yêu cầu. Gần đây tôi đã tạo biểu mẫu Đăng ký và bây giờ tôi đang tích hợp nó với API của nó. Trước đây API được chấp nhận bởi dữ liệu được mã hóa url và tất cả đều hoạt động tốt. nhưng bây giờ yêu cầu đã thay đổi và API chấp nhận dữ liệu bằng JSON, tôi phải thay đổi tiêu đề kiểu nội dung từ 'application/x-www-form-urlencoded' thành 'application/json'. Nhưng tôi nhận được lỗi sau:Không thể gửi yêu cầu đăng khi 'Loại nội dung' được đặt thành 'application/json'
Fetch API cannot load http://local.moberries.com/api/v1/candidate . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:3000 ' is therefore not allowed access. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Tôi thậm chí còn đặt 'Access-Control-Allow-Headers' trong API nhưng vẫn không hoạt động. Đây là mã có liên quan đối với các mặt hàng:
sendFormData() {
let {user} = this.props;
var formData = {
first_name: ReactDOM.findDOMNode(this.refs.firstName).value,
last_name: ReactDOM.findDOMNode(this.refs.lastName).value,
city: ReactDOM.findDOMNode(this.refs.currentCity).value,
country: ReactDOM.findDOMNode(this.refs.currentCountry).value,
is_willing_to_relocate: user.selectedOption,
cities: relocateTo,
professions: opportunity,
skills: skills,
languages: language,
min_gross_salary: minSal,
max_gross_salary: maxSal,
email: ReactDOM.findDOMNode(this.refs.email).value,
password: ReactDOM.findDOMNode(this.refs.password).value
};
var request = new Request('http://local.moberries.com/api/v1/candidate', {
method: 'POST',
mode: 'cors',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
});
var requestBody = JSON.stringify(formData);
console.log(requestBody);
fetch(request, {body: requestBody})
.then(
function (response) {
if (response.status == 200 || response.status == 201) {
return response.json();
} else {
console.log('Failure!', response.status);
}
}).then(function (json) {
var responseBody = json;
console.log(typeof responseBody, responseBody);
});
}
Và đây là mã API có liên quan:
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers: Origin, Content-Type, application/json');
}
}
Tôi thực sự không thể tìm ra vấn đề. Bất kỳ loại trợ giúp nào sẽ được đánh giá cao.
http://local.moberries.com/api/v1/candidate không thể truy cập được –
Vì địa phương là địa phương. Bạn không thể truy cập nó. –