我正在Play中构建一个RESTful API,我的路线出现了一个奇怪的错误:
# Routes
# This file defines all application routes (Higher priority routes first)
# ~~~~
# Home page
GET / controllers.Application.index()
GET /api/getMessages controllers.Application.getMessages()
POST /api/createMessage controllers.Application.createMessages(from:String, subject:String, message:String)
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
/ api / createMessage给了我一些问题,当我发布一个完整的有效负载时,我收到错误:
For request 'POST /api/createMessage' [Missing parameter: from]
控制器:
public static Result createMessages(String from, String subject, String message){
Message.create(from, subject, message);
return ok(toJson("ok"));
}
请求正文:
Request Url: http://localhost:9000/api/createMessage
Request Method: POST
Status Code: 400
Params: {
"from": "hello@test.com",
"subject": "Hello",
"message": "World"
}
有人可以帮帮我吗?
答案 0 :(得分:1)
问题是,为了通过路径文件将参数传递给Java方法,这些参数应该是端点URL的一部分,这应该类似于POST /api/createMessage/:from/:subject/:message
对于你的情况,这不是一个好主意,你想要做的事情(从json对象传递参数)实际上是要走的路。所以你应该做的是用:
替换routes文件中的行POST /api/createMessage controllers.Application.createMessages()
并使用createMessages方法读取JSON对象:
JsonNode data = request().body().asJson();
String from = data.get("from").textValue();
String subject = data.get("subject").textValue();
String message = data.get("message").textValue();
请确保您在请求中传递 Content-Type:application / json 标头,以便该游戏将请求正文理解为JSON对象。
答案 1 :(得分:0)
问题是您在请求中通过邮寄方式发送数据
尝试
GET /api/createMessage controllers.Application.createMessages(from:String, subject:String, message:String)
和
Request Method: GET
此问题是因为您的请求在POST
或者,如果你想在POST中
POST /api/createMessage controllers.Application.createMessages
控制器
public static Result createMessages{
String form = //get it
String subject = //get it
String message = //get it
//not aware of java syntax too much but get here from form
Message.create(from, subject, message);
return ok(toJson("ok"));
}
当你标记 scala 时,意味着你熟悉scala,所以在scala控制器中
def createMessages = Action{
implicit request =>
val form = request.body.asFormUrlEncoded.get("form")(0)
var subject = request.body.asFormUrlEncoded.get("subject")(0)
var message = request.body.asFormUrlEncoded.get("message")(0)
Message.create(from, subject, message)
OK("ok")
}