0

I am trying to make a post call to my (akka-http) backend from scalajs.

The same call is working in postman but failing when i am actually calling from chrome - scalajs

the code in scalajs

ext.Ajax.post(<url>, <json>, headers = Map("Content-Type" -> "application/json"))

I am getting the following error in chrome console

XMLHttpRequest cannot load <url>. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 405.

When i take a look in postman on the code for javascript (generate code snippet) i see the following

var settings = {
  "async": true,
  "crossDomain": true,
  "url": <url>,
  "method": "POST",
  "headers": {
    "content-type": "application/json",
    "cache-control": "no-cache",
    "postman-token": "273f35c9-1d2a-12d8-30d6-8523d479869e"
  },
  "processData": false,
  "data": <json>
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

As mentioned, i can access my backend from postman, not sure what i am missing in scalajs, i was thinking about the crossDomain setting, but if-so i don't know how to set it in my scalajs request.

there is probably some obvious solution.

Also get requests are actually working

EDIT: i am adding backend part akka-http router

respondWithHeaders(`Access-Control-Allow-Origin`.*, `Access-Control-Allow-Methods`(HttpMethods.GET, HttpMethods.POST),
    `Access-Control-Allow-Headers`("Origin, X-Requested-With, Content-Type, Accept, Authorization")) {
      pathPrefix("..."){...

This is the current state, so what i am missing ?

Thanks for any help.

Michal
  • 150
  • 3
  • 13

1 Answers1

1

What is happening here, is that chrome is preventing you from accessing your backend, since:

  1. The backend server is on a different domain than your JavaScript
  2. The backend server does not explicitly allow the domain your JavaScript is on to make calls (that's what the Access-Control-Allow-Origin header means).
  3. Chrome (not the backend) therefore blocks the request.

Since this check happens in the frontend/chrome, the request works very well with postman.

So to fix this properly, you should configure akka-http to add the proper Access-Control-Allow-Origin header.

If you just need to test, you can launch chrome with the flag --disable-web-security. BE VERY CAREFUL WITH THIS since it makes you (as an internet user) vulnerable to CSRF and other nasty busyness. Do not always use this flag.

gzm0
  • 14,752
  • 1
  • 36
  • 64
  • Hi and thanks for the answer, i will update my question with the code from the backend, yes i can change it but it already contains that header. Take a look. – Michal Nov 18 '15 at 19:37