1

I have an application with following back-end-technologies: scala/slick in playframework. Front- and back-end communicate via REST.

Now what I want to do is simply return a created/inserted (updated) row back to the front-end of my application. I thought about doing something like this:

def createClient = Action.async { implicit request =>
    request.body.asJson.map(_.validate[ClientModel]) match {
      case c: JsSuccess[ClientModel] =>
        clientDTO.createClient(c.get).map{
          cnt => Ok(Json.obj("id" -> cnt.id))
        }.recover {
          case e: Exception => BadRequest("Could ssnotsdreate client")
        }
    }
  }

My code compiles but it gives me this error message while running:

XMLHttpRequest cannot load http://localhost:9002/clients. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 500.

I read about adding CORS to my application but would prefer to solve it otherwise. I thought there has to be a proper, elegant way to return a just created/inserted object back to the front-end, since it should be a core feature of any client-server communication.

I'm relatively new to scala, so please don't get hung up on my code and rather view it as pseudo code. This is a rather general question. Thank you!

Nocebo
  • 1,386
  • 2
  • 10
  • 25
  • 1
    Hi Nocebo. Your code looks straightforward and elegant enough - you do the insert and you send just the id back to the caller. You'll need to solve the preflight situation, which is something you only have to do once. Do you have more questions or are you unhappy with your solution? – wwkudu Aug 01 '17 at 09:57
  • Hi wwkudu, thanks for your response. So this preflight situation is pretty common then? I'd like to renounce on importing/installing unnecessary libs. – Nocebo Aug 01 '17 at 10:14
  • 1
    CORS (and preflight) are necessary when you have two "different" apps talking, e.g. a REST client and a server. when it's a single web app you shouldn't need CORS/preflight. There's a lot of interesting discussion [in the responses to this SO question](https://stackoverflow.com/questions/15381105/cors-what-is-the-motivation-behind-introducing-preflight-requests) – wwkudu Aug 01 '17 at 13:52

0 Answers0