Fre*_*Ren 2 javascript rest cors
当我尝试将json文件发送到我的服务器时,我收到此错误.
在我的服务器端,代码是:
@POST
@Path("updatedata")
@Produces("text/plain")
@Consumes("application/json")
public Response UpdateData(String info) {
Gson gson = new Gson();
List<Data> list = gson.fromJson(info, new TypeToken<List<Data>>() {
}.getType());
int is_success = 0;
try {
is_success += trainingdata.updateData(list);
} catch (SQLException e) {
e.printStackTrace();
}
String returnjson = "{\"raw\":\"" + list.size() + "\",\"success\":\"" + is_success + "\"}";
return Response.ok().entity(returnjson).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "POST").build();
}
Run Code Online (Sandbox Code Playgroud)
我可以通过RESTClient成功更新我的数据 - 一个Chrome插件.
但是当我构建前端并尝试通过jaascript调用API时,Firefox显示:跨源请求被阻止:同源策略.... Chrome显示:XMLHttpRequest无法加载...没有'Access-Control-Allow-Origin '标头出现在请求的资源上.因此不允许原点'...'访问
我写了这样的javascript:
var json = JSON.stringify(array);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myurl:4080/updatedata", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(json);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
alert('hello');
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
Run Code Online (Sandbox Code Playgroud)
我的javascript代码有问题吗?
我将后端代码和前端代码部署在同一台机器上.
GET功能成功运行.
@GET
@Produces("application/json")
@Path("/{cat_id}")
public Response getAllDataById(@PathParam("cat_id") String cat_id) {
ReviewedFormat result = null;
try {
result = trainingdata.getAllDataById(cat_id);
Gson gson = new Gson();
Type dataListType = new TypeToken<ReviewedFormat>() {
}.getType();
String jsonString = gson.toJson(result, dataListType);
return Response.ok().entity(jsonString).header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods", "GET").build();
} catch (SQLException e) {
logger.warn(e.getMessage());
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
前端:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://URL:4080/mywebservice/v1/trainingdata/" + cat_id, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
//console.log(xhr.responseText);
var jsoninfo = xhr.responseText;
var obj = JSON.parse(jsoninfo);
}
}
}
Run Code Online (Sandbox Code Playgroud)
CORS可防止跨站点攻击发生问题,并通过不依赖其他人的资源(可能会死亡)来强制智能开发.它是大多数服务器和浏览器的默认安全功能.
在Apache中,您可以通过添加标头来禁用CORS,IIS和AppEngine的工作方式类似.
由于您在本地开发,最好的选择是XAMPP/WAMPP加上适当的标题 - 或者只是切换到FireFox.
FireFox不考虑CORS下的本地文件,而大多数浏览器都这样做.
Apache修复:
添加标题 - >
Header set Access-Control-Allow-Origin "*"
Run Code Online (Sandbox Code Playgroud)
重置服务器 - >
apachectl -t
Run Code Online (Sandbox Code Playgroud)
sudo service apache2 reload
IIS修复:
修改根目录中的web.config(类似于HTAccess)
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
Run Code Online (Sandbox Code Playgroud)
App Engine:
Python的标头方法:self.response.headers.add_header()
class CORSEnabledHandler(webapp.RequestHandler):
def get(self):
self.response.headers.add_header("Access-Control-Allow-Origin", "*")
self.response.headers['Content-Type'] = 'text/csv'
self.response.out.write(self.dump_csv())
Run Code Online (Sandbox Code Playgroud)
对于Java:resp.addHeader()
public void doGet(HttpServletRequest req, HttpServletResponse resp) {
resp.addHeader("Access-Control-Allow-Origin", "*");
resp.addHeader("Content-Type", "text/csv");
resp.getWriter().append(csvString);
}
Run Code Online (Sandbox Code Playgroud)
对于Go:w.Header().添加()
func doGet(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Content-Type", "text/csv")
fmt.Fprintf(w, csvData)
}
Run Code Online (Sandbox Code Playgroud)
如果您对此感兴趣,可以通过JSONP绕过CORS问题:http://en.wikipedia.org/wiki/JSONP
这是在javascript中发出跨域请求导致的问题.出于安全原因,浏览器会阻止此操作
在javascript中,默认情况下,您无法向其他域(包括不同的端口)发出请求.
如果需要将请求发送到另一个域,您可以选择启用CORS或使用反向代理.
归档时间: |
|
查看次数: |
16930 次 |
最近记录: |