I am creating an API by using spring boot. In this project, I used spring web, JPA, jstl and MySql as dependencies of the API. In this project, I have created a Controller, Model and Repository. Basically, this API does CRUD operations. And also I created a client that consumes my own API. When I use Postman to POST data, it successfully insert data to the database and gives me 200 OK code. Then I created web page and created a html form and used Ajax to get that data. But the thing is when I click insert button in the form, it gives me this error.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue May 01 05:16:48 IST 2018 There was an unexpected error (type=Method Not Allowed, status=405). Request method 'POST' not supported
How can I fix this ??
My controller:
package com.kisalka.pacrestapi.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.kisalka.pacrestapi.repository.ImRepository;
import com.kisalka.pacrestapi.model.ImModel;
@RestController
@RequestMapping("/api")
public class ImController {
@Autowired
private ImRepository TaskRepository;
@RequestMapping(method=RequestMethod.POST, value="/tasks")
public ImModel createNote(@RequestBody ImModel note) {
return TaskRepository.save(note);
}
}
My web page:
<form class="form-horizontal" method="POST" action="">
<div class="form-group">
<label class="control-label col-md-3">Project Name</label>
<div class="col-md-7">
<input type="text" class="form-control" name="pname" id="txtPname"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3">Developer Name</label>
<div class="col-md-7">
<input type="text" class="form-control" name="devname" id="txtDevname"/>
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Save" id="btnRegister"/>
</div>
</form>
jQuery and Ajax part:
<script type="text/javascript">
$(document).ready(function () {
// Save the new user details
$('#btnRegister').click(function () {
$.ajax({
url: '/api/tasks',
method: 'POST',
data: {
pname: $('#txtPname').val(),
devname: $('#txtDevname').val()
},
success: function () {
alert("Inserted");
},
error: function (jqXHR) {
$('#divErrorText').text(jqXHR.responseText);
$('#divError').show('fade');
}
});
});
});
</script>