【发布时间】:2018-02-02 16:50:29
【问题描述】:
我尝试使用 Rails 和 ReactJS 在我的项目中划分后端和前端。
我有一个函数可以对 POST 请求进行异步处理并使用 gem Jbuilder
生成 JSON API
JavaScript:
fetch('shops/1/deals',{
method: "POST",
body: JSON.stringify({shop_id: 1, deals_type: "workout"}),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
})
.then(function(res){
console.log(res)
res.json().then(function(data){
alert( JSON.stringify( data ) )
})
})
控制器:
def index
@shop = Shop.find(params[:id])
@deals = @shop.deals
end
def create
@deal = Deal.new(deal_params)
respond_to do |format|
if @deal.save
format.json { render :show, status: :created, location: @deal }
else
format.json { render json: @deal.errors, status: :unprocessable_entity }
end
end
end
如果我在views/deals 中有_deal.json.jbuilder 文件
json.extract! deal, :id, :shop_id, :deals_type, :created_at, :updated_at, :deal_time
我会收到警报{id: number, shop_id: 1, deals_type: "workout", .....}
但是我删除_deal.json.jbuilder文件,我会得到{}空对象。
为什么会出现问题?
【问题讨论】:
标签: javascript ruby-on-rails json fetch jbuilder