【问题标题】:POST net::ERR_ABORTED 415 (Unsupported Media Type)POST net::ERR_ABORTED 415(不支持的媒体类型)
【发布时间】:2020-09-03 08:52:28
【问题描述】:

我正在尝试通过 fetch 方法将数据从我的 React 应用程序发布到 Django REST API:

fetch('http://127.0.0.1:8000/something/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  mode: 'no-cors',
  body: JSON.stringify(this.state)
})
  .then(response => {
    console.log(response)
  })
  .catch(error => {
    console.log(error)
  })

我总是收到错误“POST http://127.0.0.1:8000/something/ net::ERR_ABORTED 415 (Unsupported Media Type)”,响应如下所示:“Response {type: "opaque", url: "", redirected: false, status :0,好的:假,...}”。 我的状态只包含空字符串(用户名:'',密码:'' 等)

我还尝试使用 axios 发送 GET 请求并在控制台中打印响应:

axios.get('http://127.0.0.1:8000/something/')
.then(function(response) {
  console.log(response);
})
.catch(function(error) {
  console.log(error)
})

但反应是:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/something/' from origin 
'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' 
header is present on the requested resource.

Error: Network Error
at createError (createError.js:16)
at XMLHttpRequest.handleError (xhr.js:83)

GET http://127.0.0.1:8000/something/ net::ERR_FAILED

你有解决这个问题的想法吗?

【问题讨论】:

    标签: django reactjs axios fetch rest


    【解决方案1】:

    由于 CORS 限制,您在 GET 请求中遇到此问题,这是一种默认浏览器限制,可防止从外部 API 获取数据。 您可以执行以下操作:

    1. 如果您使用的是 Google Chrome,请添加此扩展程序 - https://chrome.google.com/webstore/detail/who-cors/hnlimanpjeeomjnpdglldcnpkppmndbp?hl=en-GB。
    2. 重新加载浏览器选项卡。

    关于您在 POST 请求期间收到的错误 415,这是由于标头不匹配,因为您使用“no-cors”作为模式,所以您的请求标头变得不可变,因此即使您传递 'Content-Type ' 作为 'application/json',它作为 'text/char' 传递,因为这个不匹配 415 错误被抛出。您可以联系后端团队并要求他们将“Content-Type”更改为“text/char”,它应该适合您。

    【讨论】:

    • 有没有其他方法可以让我在不联系后端团队的情况下做到这一点
    • 不幸的是,没有。这是前端的死胡同,从这里你几乎无能为力,这是一个障碍,联系后端团队是唯一的出路。
    猜你喜欢
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    相关资源
    最近更新 更多