I am new here in 'stackoverflow.com'.
I have a problem with my AngularJS Application and hope that you can help me.
First of all I have created a new maven webapp project and have used the RESTful Web Serivices to get Data from my mySQL-Database. I also have used Cross-Origin Resource Sharing Filter.
For my Frontend I have created a new HTML/JS Project with a AngularJS Seed Template.
If I use the HTTP findAll() Method I get the data from Database. findAll()_XML
When I try to list my data in my AngularJS-Frontend I get this error:
XMLHttpRequest cannot load http://localhost:8080/myBackend/webresources/customer . Origin http://localhost:8383 is not allowed by Access-Control-Allow-Origin. (01:38:23:401 | error, javascript) at public_html/newhtml.html
I have red a lot of solutions to add Access-Control-Allow-Origin", "*" to the header but it does not work.
Here is my Code. I hope you can help me.
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 + " ]";
}
}
In your angularjs config file, add the following lines
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'
Also make sure in your RESTful controller, @RequestMapping has produces = "application/json"
If this does not work, add @CrossOrigin("*") above your Request mapping annotation like this
More here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.