解決scala使用play框架跨域問題

1. 如果play框架是2.5

1.1添加一個新類

 
package filters

import javax.inject.Inject
import play.api.http.DefaultHttpFilters
import play.filters.cors.CORSFilter

class CorsFilter @Inject()(corsFilter: CORSFilter)
  extends DefaultHttpFilters(corsFilter)
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

1.2 在application.conf中添加

play.http.filters = filters.CorsFilter

play.filters {
  cors {
    # Filter paths by a whitelist of path prefixes
    pathPrefixes = ["/"]
    # The allowed origins. If null, all origins are allowed.
    allowedOrigins = null
    # The allowed HTTP methods. If null, all methods are allowed
    allowedHttpMethods = ["GET", "POST"]
  }
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

1.3 在build.sbt中添加

libraryDependencies += filters
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

2. 如果play框架是2.6

2.1 在application.conf中添加

lay.filters.enabled += "play.filters.cors.CORSFilter"

play.filters.cors {
  allowedOrigins = null
}
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

2.2 在project的plugin.sbt中添加play版本 2.6.10以下好像有問題 具體可以參考 https://github.com/playframework/playframework/issues/8600

addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.17")
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

2.3 在build.sbt中添加

libraryDependencies += guice
wAAACH5BAEKAAAALAAAAAABAAEAAAICRAEAOw==

添加以上方式就可以了

如果需要在本地測試可以使用 

1,進入cmd命令行

Python2 版本輸入: python -m SimpleHTTPServer 8000

Python3 版本輸入: python -m http.server 8000

2,在瀏覽器輸入:127.0.0.1:8000 就可以訪問計算機文件了

原文在這裏 https://blog.csdn.net/a649344475/article/details/80796828

前端代碼

<?DOCTYPE html>
<html charset="utf-8">
<head>
	<meta ></meta>
	<title>test</title>
	<!-- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> -->
	<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
	<style type="text/css">
	#b01{
		width:200px;
		height:80px;
		background:pink;
		border-radius:10px;
		margin:60px 30px;
	}
	</style>
</head>

<body>
<button id="b01">test</button>
<div id="myDiv"></div>
<script type="text/javascript">
	$(document).ready(function(){
	  $("#b01").click(function(){
	  htmlobj=$.ajax({url:"http://10.10.10.107:9013/offer/getOfferList",async:false});
	  $("#myDiv").html(htmlobj.responseText);
	  });
	});
</script>
</body>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章