javascript - AngularJS MySQL REST - 来源 http ://localhost:8383 is not allowed by Access-Control-Allow-Origin

标签 javascript mysql angularjs web-applications

我是“stackoverflow.com”的新手。

我的 AngularJS 应用程序有问题,希望你能帮助我。

首先,我创建了一个新的ma​​ven webapp 项目,并使用RESTful Web 服务 从我的mySQL 数据库中获取数据。我还使用了跨源资源共享过滤器。

对于我的前端,我使用 AngularJS 种子模板创建了一个新的 HTML/JS 项目

如果我使用 HTTP findAll() 方法,我会从数据库中获取数据。 findAll()_XML

当我尝试在我的 AngularJS-Frontend 中列出我的数据时,出现此错误:

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

我有很多解决方案可以将 Access-Control-Allow-Origin", "*" 添加到 header ,但它不起作用。

这是我的代码。我希望你能帮助我。


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 Controller 中,@RequestMapping 有 produces = "application/json"

如果这不起作用,请在请求映射注释上方添加 @CrossOrigin("*") like this

更多here

关于javascript - AngularJS MySQL REST - 来源 http ://localhost:8383 is not allowed by Access-Control-Allow-Origin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40754314/

相关文章:

javascript - ext.js 消息框按钮对齐

javascript - 文档就绪给出了错误的选择器高度

javascript - 根据单独数组中的值设置数组的值 [Angular, forEach]

php - 从数据库获取数据到 session 的最有效方法

javascript - Angular SPA 中的 Google Analytics

javascript - 浮点异常浮点高度 = 0 的无效尺寸

mysql - 从 hive 检索不同的 id?

mysql - 如何限制 SQLite/MySQL 中的列值

javascript - 如何在没有拼接的情况下更新数组(angularjs)元素?

javascript - AngularJS - Uncaught Error : [$injector:modulerr] Failed to instantiate module