【问题标题】:Don't set POST request on api, get 406 Not Acceptable不要在 api 上设置 POST 请求,得到 406 Not Acceptable
【发布时间】:2018-07-15 13:27:00
【问题描述】:

不要在 api 上设置 POST 请求,得到 406 Not Acceptable。 尝试使用 axios 并得到 406 错误。有人认为是 axios 问题的原因。然后我尝试使用 fetch() 并再次遇到 406 错误。

我认为没有设置标题Content-Type,当我发送他的 - 得到 400 Bad Request 并在标签预览Unauthorized header content-type

需要你的帮助,我做错了什么? 谢谢大家的帮助。

  • 环境:node v8.9.4,chrome 64.0.3282.119,Ubuntu 16.04
  • axios 版本:0.16.2
  • Vue.js 2.4.2
  • vue-axios 2.0.2
  • api-platform/api-pack: 1.0
  • Symfony 4.0.4

Headers Review

第一个示例 fetch() 代码:

const json = JSON.stringify({
    a: 1,
    b: 2,
});
fetch('http://localhost:8080/api/products', {
    method: 'POST',
    headers: {
         // 'Content-Type': 'application/json',
    },
    body: json,
});

第二个示例 Axios 代码:

const data = JSON.stringify({
    data: this.cardData.brand,
});
const configAxios = {
    headers: {
     // 'Content-Type': 'application/json',
     },
};
axios.post('api/products', data, configAxios)
.then((res) => {
    this.cardData.brand = res.data;
    console.log(res);
})
.catch((err) => {
    console.warn('error during http call', err);
});

【问题讨论】:

  • 只是取消注释内容类型标题?它应该可以工作。
  • @DragoşPaulMarinescu 事实是它不起作用。
  • 这是服务器问题。你的服务器返回Content-Type: application/problem+json
  • @DragoşPaulMarinescu 请告诉我,如何从 api 平台的服务器发送正确的 Content-Type

标签: javascript axios fetch-api api-platform.com


【解决方案1】:

解决方案!

取消注释 axios 或 fetch() 代码中的字符串:

headers: {
     'Content-Type': 'application/json',
},

如果你使用 Symfony 4 和 am,设置 nelmio/cors-bundle,运行命令 composer req nelmio/cors-bundle。并配置nelmio_cors.yml,即添加allow_headers

nelmio_cors:
defaults:
    allow_credentials: false
    allow_origin: []
    allow_headers: ['Content-Type']
    allow_methods: []
    expose_headers: []
    max_age: 0
    hosts: []
    origin_regex: false
    forced_allow_origin_value: ~
paths:
    '^/api/':
        allow_origin: ['*']
        allow_headers: ['X-Custom-Auth', 'Content-Type']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
        max_age: 3600
    '^/':
        origin_regex: true
        allow_origin: ['^http://localhost:[0-9]+']
        allow_headers: ['X-Custom-Auth', 'Content-Type']
        allow_methods: ['POST', 'PUT', 'GET', 'DELETE']
        max_age: 3600
        hosts: ['^api\.']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2019-12-16
    • 2011-08-16
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    • 2015-03-13
    相关资源
    最近更新 更多