当“内容类型"设置为"application/json"时,无法发送发布请求 [英] Can't send a post request when the 'Content-Type' is set to 'application/json'

查看:399
本文介绍了当“内容类型"设置为"application/json"时,无法发送发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a React application and I am using fetch to send a request. I have made a Sign Up form recently and now I am integrating it with it's API. Previously the API accepted url encoded data and it was all working fine. but now that the requirement has changed and the API accepts data in JSON, I had to change the content-type header from 'application/x-www-form-urlencoded' to 'application/json'. But I get the following error:

Fetch API无法加载 http://local.moberries.com/api/v1/candidate . 对预检请求的响应未通过访问控制检查:否 请求中存在"Access-Control-Allow-Origin"标头 资源.因此,不允许使用来源" http://localhost:3000 " 使用权.如果不透明的响应满足您的需求,请设置请求的 模式设置为"no-cors",以在禁用CORS的情况下获取资源.

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.

我什至在API中设置了"Access-Control-Allow-Headers",但仍然无法使用.这是客户端的相关代码:

I have even set the 'Access-Control-Allow-Headers' in the API but it still doesn't work. Here is the relevant code for the client side:

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代码:

And here is the relevant API code:

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

我真的无法弄清楚问题所在.任何帮助将不胜感激.

I really can't figure out the problem. Any kind of help will be appreciated.

推荐答案

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

It turns out that CORS only allows some specific content types.

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

The only allowed values for the Content-Type header are:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • 文本/纯文本
  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

来源: https://developer.mozilla.org/zh- US/docs/Web/HTTP/Access_control_CORS

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

To set the content type to be 'application/json', I had to set a custom content type header in the API. Just removed the last header and added this one:

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

一切正常.

这篇关于当“内容类型"设置为"application/json"时,无法发送发布请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆