0

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

我认为没有设置标题Content-Type,当我发送 his-get 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平台/api包:1.0
  • Symfony 4.0.4

标头 审查

第一个示例 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);
});
4

1 回答 1

1

解决方案!

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

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

如果你使用 Symfony 4 as and am, setup nelmio/cors-bundle, run command 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\.']
于 2018-02-05T16:58:18.223 回答