我正在尝试将http请求从本地文件(客户端)发送到我的后端服务器。
在阅读了无数关于如何启用CROS(跨源资源共享)的文章后,我仍然收到错误:“对预检请求的响应未通过访问控制检查:否'访问控制 - 允许 - 来源'标头出现在请求的资源上。因此不允许Origin'null'访问。响应的HTTP状态代码为405.“
对于我的后端服务器,我使用Akka-Http和Spray-Json。结果,我决定使用akka-http-cors(https://github.com/lomigmegard/akka-http-cors),但这似乎也没有解决问题。我知道我应该使用options指令和'Access-Control-Allow-Origin'(fileName),但我似乎无法弄清楚如何正确使用它们。
我附上了我的后端和javascript代码的片段。如果有人知道如何在我的客户端和服务器之间正确启用CROS,这将是惊人的。
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")) )
}