2016-03-22 9 views
2

Das ist mein SkriptCross-Origin-Anforderung blockiert: in post-Methode

/** 
* 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"); 

}); 

Wenn ich $scope.deleteMovie zu schreiben ändern, bekomme ich diese

"NetworkError: 403 Forbidden - http://localhost:8181/MovieDb/delete/21 " 21 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8181/MovieDb/delete/21 . (Reason: CORS header 'Access-Control-Allow-Origin' missing).

Error: [$rootScope:inprog] http://errors.angularjs.org/1.4.8/ $rootScope/inprog?p0=%24digest

aber

Wenn ich get Methode verwenden zum Löschen bekomme ich diese Fehler https://stackoverflow.com/questions/36118718/unexpected-character-at-line-1-column-1-of-the-json-data-at-json-parse-angular

Das ist mein 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> 

Dies ist mein Controller

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"); 
    } 
} 

Ich benutze

@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? 

I corsfilter Klasse hinzugefügt, aber es kann nicht alles importieren:

enter image description here

in Controller

auch löschen und deletee doesnot Arbeit, sondern entfernt Arbeit:

@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"; 
    } 

Antwort

0

Sie habe ein paar Schritte gemacht.

  1. wenn Sie Frühlings-Java-basierte Konfiguration mit fügen Sie dann CORSFilter

    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() { 
    } 
    } 
    

ODER

  1. Sie XML-basierte Federkonfiguration dann versuchen verwenden hinzuzufügen

<context:annotation-config/> in Ihrer Spring-Konfigurationsdatei. Es unterstützt Ihre Controller-Anmerkungen.

  1. configure wie @RequestMapping unter Beispiel

    @RequestMapping(value = "/servicetest", method = {RequestMethod.GET}) 
    
  2. noch nicht funktioniert?, Dann Header von HTTP-Aufruf entfernen, nur einfachen http Anruf tätigen, wenn dieser Schritt nicht Arbeiten dann können Sie für den nächsten Schritt gehen.

  3. immer noch nicht funktioniert, dann versuchen Sie nicht, tatsächliche Entität zurückgeben nur Proxy-Objekt oder Dummy-Objekt zurück, wenn es funktioniert dann weiter.

+0

Ich tat drither vorher, aber hat nicht funktioniert. Ich machte 3 Löschmethoden in Java Controller löschen, löschen und entfernen. Nur entfernen funktioniert nur mit requestmapping ohne Wert oder Methode. Ich habe auch Klasse hinzugefügt. In angularjs während des Posts, immer noch der gleiche Fehler, aber für bekommen, hat es json erste Zeile Fehler.Ich habe auch auch Filmoption hinzufügen.Ich habe auch Fehler, aber dieses Mal, wenn ich Button hinzufügen, kann es manchmal neue Liste zeigen, aber ich kann nicht verstehen, warum auch während zeigt, gibt es auch die gleichen Fehler (vorher gab es Fehler und konnte nicht Liste aktualisieren) –

+0

Ich Ding Ihr Objekt erfolgreich gelöscht, aber es ist falsch mit Rückgabeparameter, Sie zurückgeben "String" -Objekt und Winkel will JSON Objekt. –

+0

nur versuchen Sie, leere HashMap zurück zu –

0

Headers werden sollten:

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

      }, 

Sie haben Ursprung auf Serverseite ermöglichen:

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; 
    } 
} 
+0

Immer noch gleich. '' NetworkError: 403 Verboten - http: // localhost: 8181/MovieDb/delete/21 " Cross-Origin-Anforderung blockiert: Die Richtlinie" Gleiche Herkunft "verbietet das Lesen der Remote-Ressource unter http: // localhost: 8181/MovieDb/löschen/21. (Grund: CORS-Header 'Access-Control-Allow-Origin' fehlt) ' –

+0

Sie sollten den Ursprung auf der Serverseite zulassen – Karan

+0

Ich habe ein Bild zu meiner Frage hinzugefügt, es funktioniert nicht. Es kann ContainerResponseFilter nicht importieren :( –