gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:33:38 25 4
gpt4 key购买 nike

不要在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com