几个小时以来,我一直试图让一个简单的 Ember.js 应用程序发布到 Grape API 后端,但我似乎无法让它工作。我知道 API 有效,因为我可以通过 Swagger 文档向它发布新记录,并且它们会被持久化。我知道 API 和 Ember 说得很好,因为我可以从服务器获取所有记录并在页面上与它们进行交互,而且我知道 Ember 在真空中运行良好,因为我的记录保存在本地存储中。
但是,我似乎无法让 POST 请求正常工作。它总是返回 400。我已经正确配置了 Rack-Cors,并且我在前端设置了一个 ActiveModelAdapter,在后端设置了一个 ActiveModelSerializer。
这是模型
Contact = DS.Model.extend {
firstName: DS.attr('string'),
lastName: DS.attr('string'),
email: DS.attr('string'),
title: DS.attr('string'),
createdAt: DS.attr('date'),
updatedAt: DS.attr('date')
}
和控制器
ContactsNewController = Ember.ObjectController.extend(
actions:
save: ->
@get('model').save()
cancel: ->
true
)
API 的相关部分如下所示
desc 'Post a contact'
params do
requires :first_name, type: String, desc: 'First name of contact'
requires :last_name , type: String, desc: 'Last name of the contact'
requires :email , type: String, desc: 'Email of the contact'
requires :title , type: String, desc: 'Title of the contact'
end
post do
Contact.create!(
first_name: params[:first_name],
last_name: params[:last_name],
email: params[:email],
title: params[:title]
)
end
我使用的表格是...
<form {{action 'save' on='submit'}}>
<h2>{{errorMessage}}</h2>
<label>First Name</label>
{{input value=firstName placeholder='First Name' type='text' autofocus=true}}
<label>Last Name</label>
{{input value=lastName placeholder='Last Name' type='text'}}
<label>Email</label>
{{input value=email placeholder='Email' type='text'}}
<label>Job Title</label>
{{input value=title placeholder='Job Title' type='text'}}
<hr>
<input type='submit' value='Save'>
</form>
而我得到的回应是...
{"error":"first_name is missing, last_name is missing, email is missing, title is missing"}
有接盘侠吗?对不起,我是新手。有些东西没有绑定,但我不知道为什么。
更新
更多调查...
图片:对 API cURL 的 POST 请求(通过 Postman)工作得很好。.
但是,当我从 Ember 发布时,服务器响应仍然是
{"error":"first_name is missing, last_name is missing, email is missing, title is missing"}
图片:来自 Chrome 开发工具的 POST 请求的输出如下所示
我还将控制器更改为...,这为我提供了上面 chrome 开发工具日志中的输出。
`import Ember from 'ember'`
ContactsNewController = Ember.ObjectController.extend(
actions:
createContact: ->
firstName = @get('firstName')
lastName = @get('lastName')
email = @get('email')
title = @get('title')
newRecord = @store.createRecord('contact', {
firstName: firstName,
lastName: lastName,
email: email,
title: title
})
self = this
transitionToContact = (contact) ->
self.transitionToRoute('contacts.show', contact)
newRecord.save().then(transitionToContact)
)
`export default ContactsNewController`