【问题标题】:Force Content-Type to application/json with mode no-cors使用 no-cors 模式强制 Content-Type 为 application/json
【发布时间】:2019-09-13 22:47:45
【问题描述】:

我想将内容类型强制为 application/json 但我有一个模式“no-cors”,实际上内容类型的返回是:text/plain;charset=UTF-8 当我通过时它是一样的标题,所以我不知道该怎么做。

我已经尝试使用 fetch 或 Axios,URL 在 HTTP 中,我在本地工作,所以可能是问题所在? 我试过 Postman,效果很好。

     fetch('http://link', {
            method: 'POST',
            credentials: 'include',
            redirect: 'follow',
            mode: 'no-cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "cluster_id" : [],
                "surname" :["albert"],
                "gender" :[],

            }),
        }).then((result) => {
            this.setState({ allClient: result.data }, () => {
                this.setState({ load: true })
                console.log(this.state.allClient)
        })

所以,我想要内容类型:application/json 而不是 Content-Type: text/plain;charset=UTF-8

【问题讨论】:

    标签: reactjs post content-type


    【解决方案1】:

    您提到了 CORS 和 localhost,但根据所提供的信息,我不知道您的问题与它们中的任何一个有关。

    content-type 标头指定标头后面的正文的 MIME 类型。对于您的请求,它是请求正文的类型。对于响应,它是响应正文的类型。

    您正确设置了请求的内容类型,并通过 accept 标头告诉服务器您要查找的内容,但最终由服务器端设置标头。如果您控制服务器,则可以根据需要进行调整,否则您将无法使用所提供的服务。

    【讨论】:

    • 我没有服务器的控制权。但是为什么在 Postman 中我可以收集所有数据?这个 API 被其他网站调用并且工作正常
    • @KérianPelat 如果您在浏览器上下文中,并且如您所说,CORS 未在服务器上检测为许可,那么您将无法访问 Content-Type 标头。是否发送了预检请求(如您的开发工具检查器的网络面板中所示)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 1970-01-01
    • 2012-01-30
    • 2022-01-01
    • 2018-03-17
    • 2020-04-23
    相关资源
    最近更新 更多