在我的Ruby on Rails应用程序中,我试图通过Base64格式的POSTMAN REST客户端上传一张图像。当我张贴图像时,我得到了406不可接受的响应。当我检查我的数据库,图像在那里,并成功保存。

这个错误的原因是什么,我需要在我的头文件中指定什么吗?

我的要求:

URL——http://localhost:3000/exercises.json

标题:

Content-Type  -  application/json

原始数据:

{
    "exercise": {
        "subbodypart_ids": [
            "1",
            "2"
        ],
        "name": "Exercise14"
    },
    "image_file_name": "Pressurebar Above.jpg",
    "image":"******base64 Format*******"
}

当前回答

您提到您正在使用Ruby on Rails作为后端。你没有发布相关方法的代码,但我猜它看起来像这样:

def create
  post = Post.create params[:post]
  respond_to do |format|
    format.json { render :json => post }
  end
end

改为:

def create
  post = Post.create params[:post])
  render :json => post
end

它会解决你的问题。这对我很有用:)

其他回答

如果你正在使用'request.js',你可能会使用以下代码:

var options = {
  url: 'localhost',
  method: 'GET',
  headers:{
    Accept: '*/*'
  }
}

request(options, function (error, response, body) {
  ...
})

将报头更改为接受:*/*解决了我的问题,并确保您没有任何其他接受报头

这也可能是由于防火墙阻止了请求。在我的例子中,请求有效负载包含字符串属性-“像%abc%”和&符号“&”-这导致防火墙认为这是一个安全风险(例如。一个SQL注入攻击),它阻止了请求。请注意,这里的请求并不实际发送到服务器,而是在防火墙级别本身返回。

在我的例子中,没有生成应用服务器日志,因此我知道请求实际上没有到达服务器,并且在此之前被阻止了。帮助我的日志是Web应用程序防火墙(WAF)日志。

在我的情况下,在.NET-Core中的API, API被设置为使用XML(默认设置为响应JSON),所以我在我的控制器中添加了这个注释:

[Produces("application/xml")]
public class MyController : ControllerBase {...}

谢谢你让我走上正路!

您提到您正在使用Ruby on Rails作为后端。你没有发布相关方法的代码,但我猜它看起来像这样:

def create
  post = Post.create params[:post]
  respond_to do |format|
    format.json { render :json => post }
  end
end

改为:

def create
  post = Post.create params[:post])
  render :json => post
end

它会解决你的问题。这对我很有用:)