1

I have a spring RestController which I have developed using SpringBoot.

@RestController
@RequestMapping("/myRoot")
public class MyRestController {
  @Autowired
  private MyService myService;

  @RequestMapping(value="/add/{myItem}", method=RequestMethod.POST)
  public @ResponseBody void addMyItem(@PathVariable("myItem") String myItem){
        myService.addMyItem(myItem);
    }
}

My Spring Boot class containing main method is:

@SpringBootApplication(scanBasePackages={"org.mypackage"})
public class MyRestApp {
public static void main(String[] args) {
    SpringApplication.run(MyRestApp .class, args);
}
}

When I compile the project run the generated Jar as Java Application in Eclipse, the console shows:

2017-03-17 22:33:14.363  INFO 2292 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
2017-03-17 22:33:14.371  INFO 2292 --- [           main] o.n.todo.springboot.SuperrDuperrRestApp  : Started MyRestApp in 7.056 seconds (JVM running for 7.837)

Making a post call of http://localhost:8080/MyRestApi/myRoot/add/myItem on Postman on Chrome returns success (200 OK).

This means my rest api is correctly exposed and up and running.

I am trying to call above rest URI from my AngularJs 1 app as below:

'use strict';

var myApp = angular.module("MyFirstAngularRestApp",[]);
myApp.controller("myCtrl",myCtrl);

function myCtrl($http){
  console.log("myCtrl");

  var REST_SERVICE_URI = 'http://localhost:8080/MyRestApi/';

  this.AddItem = function(newItem){
  console.log("AddItem");
  console.log(newItem);

  $http.post(this.REST_SERVICE_URI + 'myRoot/add/' + newItem).then(function(response){
        console.log("success");
    });
  }
 }

However, this is not working. I am getting the following error:

XMLHttpRequest cannot load file:///C:/myDevelopment/Angular/MyAngularApp/undefinedtoDo/add/ReadABook. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.
Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"undefinedtoDo/addItem/Read a Book","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}

I am absolutely new to AngularJs 1, so not able to understand why my rest call is not working. What am I missing?

My AngularJs project is on a different location on my laptop drive and my eclipse workspace is a different directory. But I believe this should not be of importance.

I will really appreciate, If someone can guide me how to resolve this error. Request to answer in as much detail as possible as I am new to this.

Thanks!

2 Answers 2

1

That's a cross-origin error, try annotating your controller with @CrossOrigin, it will allow your application to call the API. Using the annotation, you can specify domains (origin) and methods (PUT, GET, POST, etc). See more: http://docs.spring.io/spring-framework/docs/4.2.4.RELEASE/javadoc-api/org/springframework/web/bind/annotation/CrossOrigin.html

If you want to define the domain you want to allow, use the following piece of code in a configuration class. In this case, you don't need to annotate all your controllers:

@Bean
public WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurerAdapter() {
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**/*").allowedOrigins("locahost:8080");
        }
    };
}
Sign up to request clarification or add additional context in comments.

Comments

0

Your angular application and server are running on different origins and browsers generally, do not support that due to same-origin policy.

You can easily fix this by annotating your controller or a specific method, if you want with @CrossOrigin annotation as follows :

@CrossOrigin(origins = "http://localhost:4200", methods = { RequestMethod.POST, RequestMethod.GET, RequestMethod.DELETE,
    RequestMethod.PUT })

As you can see, you can be specific with the host or supported http methods etc.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.