我已经使用Sinatra创建了一个简单的API,它根据提交的JSON数据发送电子邮件.我可以创建一个表单,通过表单提交JSON数据,并访问params以获取电子邮件的主题,主题和正文.但是,我正在尝试使用cURL来测试API,似乎无法让事情发挥作用.我假设我在cURL请求中的格式被破坏了.下面是我尝试过的cURL请求以及params的输出以及尝试使用JSON gem解析params.
我倾向于使用一个巨大的密钥获取params,这是一个我的JSON数据字符串,其值为nil.我已经尝试添加Content-Type:application/json,当我这样做时,params是空的.
curl -X POST -H "Accept: application/json" -d '{ "to": "Brantley <test@gmail.com>", "subject": "hello world", "body": "Hi Jennifer! Sending you an email via this API I just made." }' http://localhost:9393/send-email
Run Code Online (Sandbox Code Playgroud)
这是返回的params哈希...
{"{ \"to\": \"Brantley <test@gmail.com>\", \"subject\": \"hello world\", \"body\": \"Hi Jennifer! Sending you an email via this API I just made.\" }"=>nil}
Run Code Online (Sandbox Code Playgroud)
我尝试使用JSON参数转换为更有用的东西,然后我得到以下内容......
{\"{ \\\"to\\\": \\\"Brantley <test@gmail.com>\\\", \\\"subject\\\": \\\"hello world\\\", \\\"body\\\": \\\"Hi Jennifer! Sending you an email via this API I just made.\\\" }\":null}"
Run Code Online (Sandbox Code Playgroud)
我已经花了很多时间在这上面,已经阅读了20个关于类似问题的stackoverflow帖子,并且仍然难倒,所以任何建议都会有所帮助.干杯!
我正在使用Sendgrid Parse API和Griddler gem接收传入的电子邮件.在大多数情况下,这很好用; 但是,如果您没有使用状态代码200响应Sendgrid,他们将认为应用程序没有正确接收POST请求并继续尝试发布3天的POST.我正在尝试回复状态代码并遇到问题.
在常规RESTful路由中,您可以执行类似...
render :status => 200
Run Code Online (Sandbox Code Playgroud)
但是,我相信这必须在控制器中完成以识别渲染方法.Griddler建议您创建一个EmailProcessor模型并使用"进程"方法来处理电子邮件.
据我所知,你不能在模型中使用render方法.因此,我使用类方法创建了一个EmailProcessorsController类,如下所示.
class EmailProcessor < ActiveRecord::Base
include ApplicationHelper
def initialize(email)
@email = email
@to = email.to # this is an array
@from = email.from
end
def process
# do other stuff
EmailProcessorsController.render_ok
end
end
class EmailProcessorsController < ActionController::Base
def self.render_ok
render :status => 200
end
end
Run Code Online (Sandbox Code Playgroud)
以下是我从我的应用程序获得的错误.它不喜欢渲染方法:(
NoMethodError (undefined method `render' for EmailProcessorsController:Class):
app/controllers/email_processors_controller.rb:6:in `render_ok'
app/models/email_processor.rb:16:in `process'
Run Code Online (Sandbox Code Playgroud)
我是一个新的开发者,这可能是简单的东西,但我被卡住了.任何关于问题和设计的想法和评论都非常感谢.谢谢!
UPDATE!
根据@meagar的建议,我将渲染调用移动到控制器,如下所示,但现在我得到了一个不同的错误,我不知道该怎么做.
class EmailProcessorsController < ApplicationController
def initialize(email)
@email = email
@to …Run Code Online (Sandbox Code Playgroud)