Java Intro to Java Web Development with Spark Diving into Web Development Accepting Requests

Muzhi Ou
Muzhi Ou
4,921 Points

POST ERROR: The requested route [/sign-in] has not been mapped in Spark

I tried to run the same code in Accepting request video on my computer, but spark keeps saying: The requested route [/sign-in] has not been mapped in Spark, and a 404 Not Found page keeps being returned

Can someone please help me with this? I really don't know where the problem is

Thanks!

Muzhi Ou
Muzhi Ou
4,921 Points

My code is:

public class Main {

public static void main(String[] args){

    get("/hello", (req, res) -> "Hello World");

    post("/sign-in", (req, res) -> {

        return new ModelAndView(
                new HashMap<String,String>().
                        put("name",req.queryParams("username")),
                "sign-in.hbs"
                );

    },new HandlebarsTemplateEngine());

}

}

Stuff in sign-in.hbs is the same as the one in the video. I was actually trying to make post request through query string so it was something like: localhost:4567/sign-in?username=sth

2 Answers

Seth Kroger
MOD
Seth Kroger
Treehouse Moderator 56,273 Points

You can't make a POST request with the query parameters as part of the URL. That's a GET request. POSTs send the query paramenters in the body of the request instead. If you want to make a POST, you need to submit the sign-in form in index or use a tool like Postman to submit the request.

Muzhi Ou
Muzhi Ou
4,921 Points

Thanks! I just tried using get method in spark and it worked! I still have three questions though: if http get request can also send query parameters like post request, then what is the difference between the two? Isn't that get method can do everything that post can do except that post method has to be sent through some special programs? (And maybe easier to do?)

I did tried to use telnet (without using query string) to send a post request but I still get the same results back. Why?

Also, is it because when I send localhost:4567/sign-in?username=sth to spark server, server actually receive a message saying that this is a get method, and hence it says this route is not "mapped by spark"?

Thanks very much!!

Seth Kroger
MOD
Seth Kroger
Treehouse Moderator 56,273 Points

POST and GET have different uses. GET is used for retrieving data, so a query string attached to it is related to the data you want to find. POST is used for sending data to the server (like username and password). In the REST standard, POST is specifically for creating a new resource (like creating a new login session).

/sign-in?username=foo doesn't work because it's not /sign-in. There are ways to specify the route will accept paramenters in the path Craig will get to later in the course.

Muzhi Ou
Muzhi Ou
4,921 Points

I see! Thanks!