【发布时间】:2021-03-05 21:19:39
【问题描述】:
我已经看到了相同问题的不同问题,但没有一个能解决我的错误。
我在使用表单和 axios 发布新的 campaign 记录时收到 406 Unknown format,但由于我在控制器中指定了 json 格式,所以不知道为什么:
错误
spread.js:25 POST http://localhost:4000/campaigns 406 (Not Acceptable)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Action Controller: Exception caught</title>
<header>
<h1>
ActionController::UnknownFormat
in CampaignsController#create
</h1>
</header>
路线文件
resources :campaigns
广告系列控制器
def create
@campaign = Campaign.new(campaign_params)
if current_user
@campaign.user_id = current_user.id
end
respond_to do |format|
format.json do
if @campaign.save
format.json { render :show, status: :ok, location: @campaign }
else
format.json { render json: @campaign.errors, status: :unprocessable_entity }
end
end
end
end
表格
methods: {
submit() {
var data = new FormData()
data.append('box', this.campaign.selectedBox.id)
for (const product of this.campaign.selectedProducts) {
data.append('products[]', product.id)
}
data.append('image', this.campaign.photo1)
data.append('campaign', this.campaign.id)
axios.interceptors.request.use(config => {
config.paramsSerializer = params =>
qs.stringify(params, {
arrayFormat: 'brackets',
encode: false
});
return config
})
axios.post('/campaigns', data, {
headers: {
'Content-Type': 'application/json',
}
}).then((response) => {
location.href = response.data.url
}).catch((error) => {
console.log(error.response.data)
})
},
¿我错过了什么吗?提前致谢。
【问题讨论】:
-
在调用
axios.post('/campaigns')...之前,您是否在 Axios 中设置了任何Accept-*请求标头? -
不,我在这里发布了完整的方法,我错过了什么?
-
406 错误代码通常表示客户端发出的请求带有一个或多个
Accept-*标头集。例如,客户端可以设置Accept: application/xml,但服务器无法以适当的内容类型进行响应。您是否查看了浏览器的网络检查器并验证了请求是否符合预期? -
这是我在响应头中看到的:Content-Type: text/html; charset=UTF-8,不应该是JSON吗?
-
接受:application/json, text/plain, /
标签: ruby-on-rails vue.js axios