Home > database >  Kotlin Spring - 405 response
Kotlin Spring - 405 response

Time:01-10

I am trying to go through that tutorial: https://kotlinlang.org/docs/jvm-spring-boot-add-db-support.html#add-messages-to-database-via-http-request

when I am sending post request I am getting:

{
    "timestamp": "2023-01-09T05:35:30.982 00:00",
    "status": 405,
    "error": "Method Not Allowed",
    "path": "/"
}

My code:

@SpringBootApplication
class DemoApplication

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}

@RestController
class MessageController(val service: MessageService) {
    @GetMapping("/")
    fun index(): List<Message> = service.findMessages()

    @PostMapping()
    fun post(@RequestBody message: Message) {
        service.save(message)
    }
}

data class Message(val id: String?, val text: String)

@Service
class MessageService(val db: JdbcTemplate) {
    fun findMessages(): List<Message> = db.query("select * from messages") { response, _ ->
        Message(response.getString("id"), response.getString("text"))
    }

    fun save(message: Message){
        val id = message.id ?: UUID.randomUUID().toString()
        db.update("insert into messages values ( ?, ? )",
            id, message.text)
    }
}

My request:

POST http://localhost:8080/
Content-Type: application/json

{
  "text": "Hello!"
}

CodePudding user response:

You are missing the path in the @PostMapping() annotation - see how you have it in the @GetMapping("/")

  • Related