簡體   English   中英

AngularJS MySQL REST - Access-Control-Allow-Origin不允許使用原始http:// localhost:8383

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM