阻止跨源请求:在帖子方法

时间:2016-03-22 08:09:40

标签: java angularjs json spring

这是我的剧本

  /**
 * Created by caneraydin on 16.03.2016.
 */
/**
 * Created by caneraydin on 16.03.2016.
 */
/**
 * Created by caneraydin on 16.03.2016.
 */
/**
 * Created by caneraydin on 16.03.2016.
 */
var app=angular.module('todoApp',[]);
app.controller('todoController',function($scope,$http,$window){

  //  $window.alert("in todoctrl");
    $scope.addMovie=function(title,actors){
     //   $window.alert("ititle actors "+title+actors)
      //  $scope.title="title clicked "+title;

      //  $scope.actors="actors clicked "+actors;

       // $scope.added="the movie '"+title+"' with those actors '"+actors+"' added successfully";

        $http({
            method: 'GET',
            headers: {

                "Authorization": "55d5927329415b000100003b63a9e1b480b64a1040a902a26da862d3",
                "Access-Control-Allow-Origin": "*"
            },
            url: 'http://localhost:8181/MovieDb/add/'+title+"/"+actors
        })

        $window.alert("bitiste addmovie")
        $scope.listMovie();
    },

        $scope.deleteMovie=function(id){
            $scope.id="id clicked "+id;


          //  $scope.deleted="the movie with id '"+id+"' deleted successfully";
            $window.alert("in deletemovie id"+id);

            $http({
                method: 'POST',
                headers: {

                    "Authorization": "55d5927329415b000100003b63a9e1b480b64a1040a902a26da862d3",
                    "Access-Control-Allow-Origin": "*"
                },
                url: 'http://localhost:8181/MovieDb/delete/'+id
            })


            $scope.listMovie();
        },

        $scope.editMovie=function(id){
            $scope.id="id clicked "+id;




            //  $scope.deleted="the movie with id '"+id+"' deleted successfully";
            $window.alert("in edittemovie id"+id);
            listMovie();
        },


        $scope.listMovie=function(){
      //      var list = 1
        //    $window.alert("in listmovie");
            $scope.check='NO';
        //    $scope.list="list clicked "+list;
         //   $window.alert(" listmovie "+list);
          // $scope.listed="the movies are listing: "+list;
            $http({
                method: 'GET',
                headers: {

                    "Authorization": "55d5927329415b000100003b63a9e1b480b64a1040a902a26da862d3",
                    "Access-Control-Allow-Origin": "*"
                },
                url: 'http://localhost:8181/MovieDb/list'
            }).then(function successCallback(response) { $window.alert("in listmoviesuccess");
              //  $scope.check = response.data;
                console.log(response);
              $scope.tasks = response.data;
            //    $scope.names = response.data.title;



            }, function errorCallback(response) {$window.alert("in listmovie err");
              //  console.log(response);
               // $scope.check = response;
            }
            );

            //$window.alert("in listmovie end");
        };
    //$window.alert("after listmovieq");
    $scope.listMovie();

    //$window.alert("after listmovie");

});

当我将$scope.deleteMovie更改为发布时,我会收到此

  

" NetworkError:403禁止 -   http://localhost:8181/MovieDb/delete/21"       21       跨源请求已阻止:同源策略禁止读取远程资源   http://localhost:8181/MovieDb/delete/21。 (原因:CORS标题   '访问控制允许来源'丢失)。

     

错误:[$ rootScope:inprog]   http://errors.angularjs.org/1.4.8/ $ rootScope / inprog?P0 =%24digest

但是

当我使用get方法进行删除时,我会收到这些错误 https://stackoverflow.com/questions/36118718/unexpected-character-at-line-1-column-1-of-the-json-data-at-json-parse-angular

这是我的HTML:

   <!DOCTYPE html>
<html ng-app="todoApp">
<head><script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="script.js"></script></head>
<!--//<head>
   // <script>

      //  var app=angular.module('todoApp',[]);
      //  app.controller('todoController',function($scope, $rootScope) {


                //for (var i = 1; i <= 3; i++) {
                 //  $rootScope.list = '1afsdasasda'
           //         $rootScope.list= "asdasasda"
                    //alert("Rabbit " + i + " out of the hat!");


        //    }
       // })

    //</script>

//</head>-->

<body>
<div class="main-container" ng-controller="todoController">
    <div class="client-area">
        <label fo.table-container tabler="txt"></label>

         <input type="text" ng-model="title" placeholder="enter movie name here">
        <input type="text" ng-model="actors" placeholder="enter movie actors here">
        <!--<p>lsist :{{list}}</p>-->
        <button ng-click="addMovie(title,actors)">Add Movie</button>
        <table id="tab">
            <thead>
            <tr><th>Actors</th><th>ID</th><th>Name</th><th colspan="2">Options</th></tr>
            </thead>
            <tbody>


            <tr ng-repeat="task in tasks">
                <td ng-repeat="(key, val) in task">{{val}}   </td><td>

                <button ng-click="editMovie(task.id)">Edit</button><button ng-click="deleteMovie(task.id)">Delete</button></td>
            </tr>


            </tbody>
        </table>
    </div>
</div>
</body>
</html>

这是我的控制器

  package com.example;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.util.List;

/**
 * Created by caneraydin on 15.03.2016.
 */


@CrossOrigin(origins = "http://localhost:63342", maxAge = 3600)
@RestController
public class MovieController {

    @Autowired
    private MovieRepository movieRepository;


    @RequestMapping("/home")
    public String home() {
        System.out.println("moviecontroller homeda");
        return "index";
    }

    @RequestMapping("/add/{title}/{actors}")
    public String add(@PathVariable String title, @PathVariable String actors) {
        System.out.println("moviecontroller addeda");

        Movie movie = new Movie(title, actors);
        movieRepository.save(movie);
        return "added";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable long id) {
        System.out.println("moviecontroller deleteda");


        movieRepository.delete(id);

        return "deleted";
    }

    @RequestMapping("/list")
    public List<Movie> list() {
        System.out.println("moviecontroller list");


        return movieRepository.findAll();
    }

    @RequestMapping("/edit/{id}/{title}/{actors}")
    public String edit(@PathVariable long id,@PathVariable String actors,@PathVariable String title) {
        System.out.println("moviecontroller editta");
        Movie movie =   movieRepository.findOne(id);
        movie.setActors(actors);
        movie.setTitle(title);
        movieRepository.save(movie);
       // movieRepository.edit(id);
        return "edited";
    }


    @RequestMapping(method = RequestMethod.GET)
    public String getIndexPage() {
        return "index.html";
    }

    //@RequestMapping("/")
   // public String index() {
   //     return "index.html";
    //}



}

@Controller
class IndexController{

@RequestMapping("/")
public String index() {
        return "index.html";
        }

        }

@Configuration
class DefaultView extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/main/resources/static/index.html");
    }
}

我用

 @CrossOrigin(origins = "http://localhost:63342", maxAge = 3600) for cors errors but still got it. What am i doing wrong?  I dont need get for delete. Should i use http also in controller?

我添加了corsfilter类但它无法导入任何内容:

enter image description here

同样在控制器中,删除和删除不起作用但删除了工作:

@RequestMapping(value="/delete/{id}",method = { RequestMethod.POST, RequestMethod.DELETE })
    public String delete(@PathVariable long id) { 
        System.out.println("moviecontroller deleteda");


        movieRepository.delete(id);

        return "deleted";
    }

    @RequestMapping(value="/deletee",method = { RequestMethod.POST, RequestMethod.DELETE })
    public String deletee(@RequestParam("id") long id){
        System.out.println("moviecontroller deleteeda");


        movieRepository.delete(id);

        return "deleteed";
    }

    @RequestMapping("/remove/{id}")
    public String remove(@PathVariable long id) {
        System.out.println("moviecontroller removeda");


        movieRepository.delete(id);

        return "removed";
    }

2 个答案:

答案 0 :(得分:0)

标题应为:

headers: {
                    "Authorization": "55d5927329415b000100003b63a9e1b480b64a1040a902a26da862d3",
                    "Access-Control-Allow-Origin": "*", 
                    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"

          },

您必须在服务器端允许原点:

package your.package;

public class CORSFilter implements ContainerResponseFilter {

    @Override
    public ContainerResponse filter(ContainerRequest creq, ContainerResponse cresp) {

        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Origin", "*");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Credentials", "true");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS, HEAD");
        cresp.getHttpHeaders().putSingle("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");

        return cresp;
    }
}

答案 1 :(得分:0)

你已经遵循了一些步骤。

  1. 如果您使用基于Spring Java的配置,则添加CORSFilter

    import java.util.Timer;
    import java.util.TimerTask;
    
    public class Tester {
    
        public static void main(String args[]) {
    
            String[] fname = { "file1.txt", "file2.txt", "file3.txt", "file4.txt", "file5.txt" };
            for (int i = 0; i < 5; i++) {
                try {
    
                    MyRunnableThread mrt = new MyRunnableThread(fname[i]);
                    Thread t = new Thread(mrt);
                    t.start();
    
                    final Timer timer = new Timer();
                    timer.scheduleAtFixedRate(new TimerTask() {
                        int i = 6; // Time in seconds
    
                        public void run() {
                            System.out.println(i--);
                            if (i < 0) {
                                timer.cancel();
                                mrt.setRun(false);
                            }
                        }
                    }, 0, 1000);
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
  2. OR

    1. 您正在使用基于xml的弹簧配置,然后尝试添加
    2. public class CORSFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { System.out .println("Filtering on..........................................................."); HttpServletResponse response = (HttpServletResponse) res; response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE"); response.setHeader("Access-Control-Max-Age", "3600"); response.setHeader("Access-Control-Allow-Headers", "x-requested-with, Content-Type"); chain.doFilter(req, res); } public void init(FilterConfig filterConfig) { } public void destroy() { } } 在Spring配置文件中。它将支持您的控制器注释。

      1. 配置@RequestMapping,如下例

        <context:annotation-config/>
      2. 仍然不能正常工作?,然后从http调用中删除标题,只需进行简单的http调用,如果此步骤不起作用,则可以进行下一步。

      3. 仍然没有工作,那么不要尝试返回实际实体只返回代理对象或虚拟对象,如果它正常工作则继续。