当'Content-Type'设置为'application / json'时,无法发送帖子请求

问题描述 投票:10回答:2

我正在研究React应用程序,我正在使用fetch来发送请求。我最近制作了一个Sign Up表单,现在我正在将它与它的API集成。以前,API接受了url编码数据,并且一切正常。但是现在需求已经改变并且API接受JSON中的数据,我不得不将内容类型头从'application / x-www-form-urlencoded'更改为'application / json'。但是我收到以下错误:

Fetch API无法加载http://local.moberries.com/api/v1/candidate。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,'http://localhost:3000'原产地不允许进入。如果不透明响应满足您的需求,请将请求的模式设置为“no-cors”以获取禁用CORS的资源。

我甚至在API中设置了“Access-Control-Allow-Headers”,但它仍然无效。以下是客户端的相关代码:

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);
    });

  }

以下是相关的API代码:

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');
    }
}

我真的无法弄清楚问题。任何形式的帮助将不胜感激。

json reactjs cors fetch content-type
2个回答
21
投票

事实证明,CORS只允许某些特定的内容类型。

Content-Type标头唯一允许的值是:

  • 应用程序/ x-WWW窗体-urlencoded
  • 多部分/格式数据
  • 纯文本/

资料来源:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

要将内容类型设置为“application / json”,我必须在API中设置自定义内容类型标头。刚删除了最后一个标题并添加了这个标题:

->header('Access-Control-Allow-Headers', 'Content-Type');

它运作良好。


0
投票

你违反了'Same Origin Policy'。网站www.example.com可能永远无法从任何网站www.example.net加载资源而非自身。

然而,在开发过程中,有时需要能够做到这一点。绕过这个:

  1. 要么将你的起源移到http://local.moberries.com
  2. 或将api(您正在访问的)移动到您的localhost。
  3. 除此之外,还有一些方法可以在某些浏览器(特别是Chrome)中临时关闭这些类型的限制,这些方法通常需要在浏览器的后续更新中付出更多努力。在Google上搜索有关如何在您的浏览器版本中启用跨源资源共享的信息。
  4. 或者,如错误提示所示,引入一个标题,允许从非来源接受请求。更多信息请访问the documentation for Access Control CORS
© www.soinside.com 2019 - 2024. All rights reserved.