jsonpWithParameter

Wraps a response of type application/json with an invocation to a callback function which name is given as an argument. The new type of the response is application/javascript.

Signature

def jsonpWithParameter(parameterName: String): Directive0 

Description

Find more information about JSONP in Wikipedia. Note that JSONP is not considered the solution of choice for many reasons. Be sure to understand its drawbacks and security implications.

Example

case class Test(abc: Int)
object TestProtocol {
  import spray.json.DefaultJsonProtocol._
  implicit val testFormat = jsonFormat(Test, "abc")
}
val route =
  jsonpWithParameter("jsonp") {
    import TestProtocol._
    import spray.httpx.SprayJsonSupport._
    complete(Test(456))
  }

Get("/?jsonp=result") ~> route ~> check {
  responseAs[String] ===
    """result({
      |  "abc": 456
      |})""".stripMarginWithNewline("\n")
  contentType === MediaTypes.`application/javascript`.withCharset(HttpCharsets.`UTF-8`)
}
Get("/") ~> route ~> check {
  responseAs[String] ===
    """{
      |  "abc": 456
      |}""".stripMarginWithNewline("\n")
  contentType === ContentTypes.`application/json`
}