javascript - 不要在 api 上设置 POST 请求,得到 406 Not Acceptable

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

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

我认为未设置 header 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 平台/api 包: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);
});

最佳答案

解决方案!

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

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

如果您当前使用 Symfony 4,请设置 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\.']

关于javascript - 不要在 api 上设置 POST 请求,得到 406 Not Acceptable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48626826/

相关文章:

javascript - JQuery 和 Javascript 在我的项目中不起作用,但在网络上可以

javascript - 使用 node.js 连接和聚合 json 响应数据

vue.js - 动态更改axios代理URL的正确方法?

javascript - IE11 对于无缓存请求返回 304

cors - Fetch 拒绝 404 响应的 promise ,而不是使用 404 状态进行解析

用于检查字符串中是否只有数字或小数的 JavaScript 函数

javascript - 著名的gl是什么?

http - 无法访问前端应用程序中的自定义响应 header

javascript - 如何从对象列表创建键值对象

javascript - 如何使用 fetch 发布图片?