Justin Strong
11/24/2022, 12:28 PMclass Articles(val sort: String? = "new") {
@Serializable
@Resource("new")
class New(val parent: Articles = Articles())
@Serializable
@Resource("{id}")
class Id(val parent: Articles = Articles(), val id: Long) {
@Serializable
@Resource("edit")
class Edit(val parent: Id)
}
}
fun Application.configureRouting() {
println("routing")
// Starting point for a Ktor app:
routing {
/*get<Articles> { article ->
// Get all articles ...
call.respondText("List of articles sorted starting from ${article.sort}")
}*/
post<Articles> { article ->
println("posty time")
// Get all articles ...
call.respondText("posty")
}
post<Articles.New> {
var headers = call.request.headers;
println(headers)
println(call.request.headers.toString())
// Show a page with fields for creating a new article ...
call.respondText("Create a new article")
}
get<Articles.New> {
// Save an article ...
println(call.request.toString())
call.respondText("An article is saved", status = HttpStatusCode.Created)
}
}
}
And here’s the TypeScript sending the requests
function sendPostRequest() {
fetch('<http://localhost:8080/articles/new>',
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'no-cors',
method: "POST",
//body: JSON.stringify({firstName: "Jet", lastName: "woooooooooo", numba: 1})
})
.then(response => response.text())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
function sendGetRequest() {
fetch('<http://localhost:8080/articles/new>',
{
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'no-cors',
method: "GET",
})
.then(response => response.text())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
}
Rustam Siniukov
11/24/2022, 1:04 PM.post
method is imported from .resources
package and not from .routing
Justin Strong
11/24/2022, 2:20 PMJustin Strong
11/24/2022, 2:20 PMimport <http://io.ktor.server.resources.post|io.ktor.server.resources.post>
Justin Strong
11/24/2022, 2:21 PMimport io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.response.*
import io.ktor.server.request.*
import com.thefitpassport.op.opSignup
import io.ktor.resources.*
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.routing.*
import io.ktor.server.plugins.cors.routing.*
import java.lang.Exception
import io.ktor.server.plugins.contentnegotiation.*
import io.ktor.server.resources.*
import io.ktor.server.resources.Resources
import io.ktor.server.routing.delete
import io.ktor.server.routing.get
import <http://io.ktor.server.resources.post|io.ktor.server.resources.post>
import io.ktor.server.routing.put
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.JsonObject