带有 Akka-Http 和 Spray 的 CORS

CORS with Akka-Http and Spray

我正在尝试将 HTTP 请求从本地文件(客户端)发送到我的后端服务器。

在阅读了无数关于如何启用 CROS(跨源资源共享)的文章后,我仍然遇到错误:"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."

对于我的后端服务器,我使用 Akka-Http 和 Spray-Json。因此,我决定使用 akka-http-cors (https://github.com/lomigmegard/akka-http-cors),但这似乎也没有解决问题。我知道我应该使用选项指令和 'Access-Control-Allow-Origin'(fileName),但我似乎无法弄清楚如何正确使用它们。

我附上了我的后端片段和 javascript 代码。如果有人知道如何在我的客户端和服务器之间正确启用 CROS,那就太棒了。

Backend scala-akka-spray code

var signInUrl = 'http://0.0.0.0:8080/user/sign-in';

function sendEntry(form, signType) {
  var jsonString = serializeEntry(form);
  
  var httpRequest = new XMLHttpRequest();
  httpRequest.open('POST', signInUrl, true); // true meanining asynchronous
  httpRequest.setRequestHeader('Content-type', 'application/json');
  httpRequest.send(jsonString);
}

我能够通过 https://dzone.com/articles/handling-cors-in-akka-http

中列出的代码实现此功能

复制到这里完成:

import akka.http.scaladsl.model.HttpMethods._
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.model.{HttpResponse, StatusCodes}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.directives.RouteDirectives.complete
import akka.http.scaladsl.server.{Directive0, Route}

import scala.concurrent.duration._


/**
  * From https://dzone.com/articles/handling-cors-in-akka-http
  *
  *
  */
trait CORSHandler {

  private val corsResponseHeaders = List(
    `Access-Control-Allow-Origin`.*,
    `Access-Control-Allow-Credentials`(true),
    `Access-Control-Allow-Headers`("Authorization",
      "Content-Type", "X-Requested-With"),
    `Access-Control-Max-Age`(1.day.toMillis)//Tell browser to cache OPTIONS requests
  )
  //this directive adds access control headers to normal responses
  private def addAccessControlHeaders: Directive0 = {
    respondWithHeaders(corsResponseHeaders)
  }
  //this handles preflight OPTIONS requests.
  private def preflightRequestHandler: Route = options {
    complete(HttpResponse(StatusCodes.OK).
             withHeaders(`Access-Control-Allow-Methods`(OPTIONS, POST, PUT, GET, DELETE)))
  }
  // Wrap the Route with this method to enable adding of CORS headers
  def corsHandler(r: Route): Route = addAccessControlHeaders {
    preflightRequestHandler ~ r
  }
  // Helper method to add CORS headers to HttpResponse
  // preventing duplication of CORS headers across code
  def addCORSHeaders(response: HttpResponse):HttpResponse =
    response.withHeaders(corsResponseHeaders)
}

用作:

private val cors = new CORSHandler {}

val foo: Route = path("foo") {
    //Necessary to let the browser make OPTIONS requests as it likes to do 
    options {
      cors.corsHandler(complete(StatusCodes.OK))
    } ~ post( cors.corsHandler(complete("in foo request")) )
  }

更多详情:https://ali.actor/enabling-cors-in-akka-http/

可能对某人有用:我刚刚添加了一个 cors() 指令,它对我有用:

import ch.megard.akka.http.cors.scaladsl.CorsDirectives.cors

val route: Route = cors() {    // cors() may take optional CorsSettings object
  get {...}
}