Reputation: 38958
When I post data to a Scalatra route, no params are seen.
On the client:
$.ajax({
type: 'POST',
url: window.location.origin + '/move',
contentType: 'application/octet-stream; charset=utf-8',
data: {gameId: 1, from: from.toUpperCase(), to: to.toUpperCase()},
success: function(result) {
console.log('ok posting move', result);
},
error: function(e) {
console.log('error posting move', e);
}
});
In dev tools network view:
Payload
gameId=1&from=B1&to=C3
In Scalatra route:
params("gameId") // -> java.util.NoSuchElementException: key not found: gameId
However, if I change the ajax call by removing the data field and setting the url to:
type: 'POST',
url: window.location.origin + '/move?gameId=1&from=' +
from.toUpperCase() + '&to=' + to.toUpperCase(),
Then Scalatra can see the params OK, even though it seems wrong to put params in the query string for a post.
Why can't Scalatra see any params when posting data?
Upvotes: 0
Views: 448
Reputation: 1587
You need to use application/x-www-form-urlencoded
as content type:
script(type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js")
:javascript
$(function() {
$("#btn").click(function() {
$.ajax({
type: 'POST',
url: window.location.origin + '/form',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: {gameId: 1, from: "FROM", to: "TO"}
});
});
});
span#btn hello
In your Scalatra application:
post("/form") {
val payload = for {
gameId <- params.getAs[Int]("gameId")
from <- params.getAs[String]("from")
to <- params.getAs[String]("to")
} yield (gameId, from, to)
payload
}
For details please take a look at the Servlet specification.
Upvotes: 1