【问题标题】:Rails + Vue.js axios POST getting 406 Unknown ErrorRails + Vue.js axios POST 得到 406 未知错误
【发布时间】: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


【解决方案1】:

上面的代码使用的是 Rails 资源(routes.rb),没有定义默认格式,Axios POST 请求没有指定格式。

当您提交 POST 请求时,请检查 rails 服务器日志并查看控制器如何处理请求。我预计以上内容将生成以下行:“由 CampaignsController#create 作为 HTML 处理”。

尝试在路由文件 (https://guides.rubyonrails.org/routing.html#defining-defaults) 中定义默认格式:

defaults format: :json do
  resources :campaigns
end

或指定 POST 请求的格式。

axios.post('/campaigns.json', ...)...

【讨论】:

    猜你喜欢
    • 2020-05-22
    • 1970-01-01
    • 2019-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-18
    • 1970-01-01
    相关资源
    最近更新 更多