2

I am trying to make a http call from angularjs in spring controller and post json data but I am getting this error in angularjs :

angular.js:10661 POST http://localhost:8080/shopng/product/add 404 (Not 
Found)
(anonymous) @ angular.js:10661
sendReq @ angular.js:10480
serverRequest @ angular.js:10187
processQueue @ angular.js:14634
(anonymous) @ angular.js:14650
$eval @ angular.js:15916
$digest @ angular.js:15727
$apply @ angular.js:16024
(anonymous) @ angular.js:23416
eventHandler @ angular.js:3293
product_service.js:35 Error while adding product
product_controller.js:30 {productName: "ads", productPrice: 34, description: "ads", imageUrl: "asd"}

But when I use GET request then it's not giving me any error but it says media type not supported and when I remove the media type and perform then 'NULL' value is added in database.

Here is my RestController:

@RestController
@RequestMapping("/product")
public class ProductRestController {
@Autowired
ProductDao productDao;
//Add Product

 @RequestMapping(value = "/add", method= RequestMethod.POST, consumes="application/json")
    public ResponseEntity<Void> createProduct(@ModelAttribute("product") Product product) {
        System.out.println("Creating Product " + product.getProductName());

        if (productDao.isProductExit(product)) {
            System.out.println("A Product with name " + product.getProductName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

       productDao.add(product);

       return new ResponseEntity<Void>(HttpStatus.CREATED);
    }

Here is my angular's service making request:

function addProduct(product){
    var deferred = $q.defer();
    $http.post('http://localhost:8080/shopng/product/add', product)
        .then(
           function(response){
               deferred.resolve(response.data);
           },
           function(errResponse){
               console.log('Error while adding product');
               deferred.reject(errResponse);
           }

        );
    return deferred.promise;
 }

here is my github repo of the project : https://github.com/Bk073/Shopping Any help would be appreciated.

  • Are you sure your mapping is correct? Can u post your complete controller including the request mapping on the class. – Indraneel Bende Jun 04 '18 at 01:43
  • This question is related to spring boot and not angularjs. – Ashish Santikari Jun 04 '18 at 02:42
  • @IndraneelBende thank you for your response and yes the mapping is correct. I have posted the same question I will share you the link and you may have a look at all the values. https://stackoverflow.com/questions/50658617/error-while-sending-json-from-angular-to-spring-controller/50659157?noredirect=1#comment88328854_50659157 –  Jun 04 '18 at 02:49
  • @IndraneelBende Thats the same problem only the servlet is different i.e ' localhost:8080/shopng ' in this case and in there it is 'localhost:8080/shopping' –  Jun 04 '18 at 02:52
  • in that example i dont see where are u adding /shopng or /shopping in the rest controller – Indraneel Bende Jun 04 '18 at 03:14
  • @IndraneelBende do you mind if send the zip of the project ? –  Jun 04 '18 at 05:08
  • Have you enabled the CSRF? – Supun Dharmarathne Jun 04 '18 at 10:27
  • @SupunDharmarathne Yes CSRF is enabled and I tried disabling it also. –  Jun 04 '18 at 11:12
  • I'm assuming that's a typo in the URL's context-root? Your other question has "shoping", this one has "shopng", without the "i". – dbreaux Jun 04 '18 at 12:31
  • have you tried to had headers to your post request on the angular side ? – Loïc Thierry Jun 04 '18 at 12:37
  • @LoïcThierry No I haven't tried using headers on the post request on the angular side. It is giving me data in Json form. Should I have to add headers there ? –  Jun 04 '18 at 12:55
  • you can try it I don't know if it'll work but I had a similar issu with angular2 so it can work. Angular didn't add the header automatically so it ended up with an error – Loïc Thierry Jun 04 '18 at 12:59
  • @LoïcThierry but i don't think the issue is there. I think the issue is with the controller class –  Jun 04 '18 at 13:02
  • do you see the output of the prints ? if yes this is not the problem – Loïc Thierry Jun 04 '18 at 13:03
  • No i dont see the output of the print. –  Jun 04 '18 at 13:05
  • either it's a problem with the headers or the path I look into your project and a didn't see where you add the /shopng to your path (maybe the missing i is the issue too) – Loïc Thierry Jun 04 '18 at 13:08
  • @IndraneelBende now I have added the rest of the code as you have said so there is "/product" mapping in the controller and the shopng is the servlet context –  Jun 04 '18 at 13:15
  • @LoïcThierry I have added the path in the URI 'http://localhost:8080/shopng/product/add' –  Jun 04 '18 at 13:17
  • Have you tried this request with POSTMAN or any other client? – Supun Dharmarathne Jun 04 '18 at 15:46
  • @SupunDharmarathne Yes I have tried and it is giving me 404 error too –  Jun 05 '18 at 01:07

3 Answers3

1

I have gone through your securityconfig class.

Please disable the csrf as below.

http.authorizeRequests().antMatchers("/admin/**")
    .access("hasRole('ROLE_ADMIN')").and().formLogin()
    .loginPage("/login").failureUrl("/login?error")
    .usernameParameter("username")
    .passwordParameter("password")  
    .and().logout().logoutSuccessUrl("/login?logout")
    .and().csrf().disable();
    //.and().exceptionHandling().accessDeniedPage("/403");

You are getting 404 - because the csrf check is throwing an exception. To handle that exception, you have not added an exception handler. So the 404 means - exception handler is not found, not the post request itself.

If you need to secure with csrf, keep in mind to send csrf token with the request.

Please see the below attachment with successful response.

enter image description here

updated code https://github.com/supun/Shopping

Supun Dharmarathne
  • 1,138
  • 1
  • 10
  • 19
0

The value property in your controller is incorrect. It should start with / . Please change to /add in your controller

//Add Product

 @RequestMapping(value = "/add", method= RequestMethod.POST, consumes="application/json")
    public ResponseEntity<Void> createProduct(@ModelAttribute("product") Product product) {
        System.out.println("Creating Product " + product.getProductName());

        if (productDao.isProductExit(product)) {
            System.out.println("A Product with name " + product.getProductName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

       productDao.add(product);

       return new ResponseEntity<Void>(HttpStatus.CREATED);
    }
Akshay Pethani
  • 2,390
  • 2
  • 29
  • 42
0

Try something like this. Add RequestBody instead of ModelAttribute.

@RequestMapping(value = "/add", method= RequestMethod.POST, consumes="application/json")
    public ResponseEntity<Void> createProduct(@RequestBody  Product product) {
        System.out.println("Creating Product " + product.getProductName());

        if (productDao.isProductExit(product)) {
            System.out.println("A Product with name " + product.getProductName() + " already exist");
            return new ResponseEntity<Void>(HttpStatus.CONFLICT);
        }

       productDao.add(product);

       return new ResponseEntity<Void>(HttpStatus.CREATED);
    }
Supun Dharmarathne
  • 1,138
  • 1
  • 10
  • 19