user6089500
user6089500

Reputation:

Cross-Origin Request Blocked: in post method

This is my script

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

});

When i change $scope.deleteMovie to post, i get this

"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

but

When i use get method for deleting, i get those errors https://stackoverflow.com/questions/36118718/unexpected-character-at-line-1-column-1-of-the-json-data-at-json-parse-angular

This is my 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>

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

I use

 @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 added corsfilter class but it cant import anything:

enter image description here

Also in controller , delete and deletee doesnot work but removes work:

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

Upvotes: 2

Views: 3060

Answers (2)

Vinit Solanki
Vinit Solanki

Reputation: 2023

you have follow some steps.

  1. if you are using Spring Java Based configuration then add 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() {
     }
     }
    

OR

  1. you are using xml based spring configuration then try to add

<context:annotation-config/> in your Spring configuration file. It will support your controller annotations.

  1. configure @RequestMapping like example below

     @RequestMapping(value = "/servicetest", method = {RequestMethod.GET})
    
  2. still not working ?, then remove header from http call, just make simple http call, if this step not working then you can go for next step.

  3. still not working then don't try to return actual entity just return proxy object or dummy object, if its working then go ahead.

Upvotes: 1

Karan
Karan

Reputation: 1118

Headers Should be:

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

          },

You have to allow origin on server side:

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

Upvotes: 0

Related Questions