![](/img/trans.png)
[英]Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin
[英]AngularJS MySQL REST - Origin http://localhost:8383 is not allowed by Access-Control-Allow-Origin
我是'stackoverflow.com'的新用户。
我的AngularJS应用程序有问题,希望你能帮助我。
首先,我创建了一个新的maven webapp项目 ,并使用RESTful Web服务从mySQL-Database中获取数据。 我也使用了跨源资源共享过滤器。
对于我的前端,我使用AngularJS种子模板创建了一个新的HTML / JS项目 。
如果我使用HTTP findAll()方法,我从数据库中获取数据。 的findAll()_ XML
当我尝试在AngularJS-Frontend中列出我的数据时,我收到此错误:
XMLHttpRequest无法加载http:// localhost:8080 / myBackend / webresources / customer 。 Access-Control-Allow-Origin不允许使用origin http:// localhost:8383 。 (01:38:23:401 |错误,javascript)在public_html / newhtml.html
我有很多解决方案来添加Access-Control-Allow-Origin“,”*“到标题但它不起作用。
这是我的代码。 我希望你能帮助我。
services.js:
'use strict';
var customerServices = angular.module('myApp.services', ['ngResource']);
customerServices.factory('Customers', function($resource) {
return $resource('http://localhost:8080/myBackend/webresources/customer', {}, {
findAll:{method:'GET',isArray:true}
});
});
dbController.js:
'use strict';
angular.module('myApp', ['myApp.services'])
//controller Example 2
//controller Example 3
.controller('dbController', function($scope, Customers) {
$scope.allcustomers = Customers.findAll();
});
newHtml.html:
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html ng-app="myApp">
<head>
<title>Example-Applikation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-resource.js"></script>
<script src="js/friendsController.js"></script>
<script src="js/services.js"></script>
<script src="js/dbController.js"></script>
</head>
<body>
<br>
<div ng-controller="dbController">
DB-Test:
<ul>
<li ng-repeat="onecustomer in allcustomers">
Customer: {{onecustomer.email}}
</li>
</ul>
</div>
</body>
</html>
NewCrossOriginResourceSharingFilter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.mybackend;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.ext.Provider;
/**
*
* @author
*/
@Provider
public class NewCrossOriginResourceSharingFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext response) {
response.getHeaders().putSingle("Access-Control-Allow-Origin", "*");
response.getHeaders().putSingle("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE");
response.getHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type");
}
}
Customer.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.mybackend;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author loni
*/
@Entity
@Table(name = "customer")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Customer.findAll", query = "SELECT c FROM Customer c")
, @NamedQuery(name = "Customer.findById", query = "SELECT c FROM Customer c WHERE c.id = :id")
, @NamedQuery(name = "Customer.findByName", query = "SELECT c FROM Customer c WHERE c.name = :name")
, @NamedQuery(name = "Customer.findByEmail", query = "SELECT c FROM Customer c WHERE c.email = :email")
, @NamedQuery(name = "Customer.findByTel", query = "SELECT c FROM Customer c WHERE c.tel = :tel")})
public class Customer implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "name")
private String name;
// @Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "email")
private String email;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 100)
@Column(name = "tel")
private String tel;
public Customer() {
}
public Customer(Integer id) {
this.id = id;
}
public Customer(Integer id, String name, String email, String tel) {
this.id = id;
this.name = name;
this.email = email;
this.tel = tel;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Customer)) {
return false;
}
Customer other = (Customer) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
@Override
public String toString() {
return "com.mycompany.mybackend.Customer[ id=" + id + " ]";
}
}
在angularjs配置文件中,添加以下行
angular.module('yourapp')
.config('$httpProvider',function($httpProvider){
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json';
$httpProvider.defaults.headers.put['Content-Type'] = 'application/json';
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
});
//since your getting your data in xml format, instead of application/json, put the content-type as 'application/xml'
还要确保在RESTful控制器中,@ RequestMapping已生成=“application / json”
如果这不起作用,请在Request映射注释上方添加@CrossOrigin(“*”), 如下所示
更多这里
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.