Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialNelson Fleig
25,764 PointsWhat's wrong with my code? It compiles and works fine in IDE
The redirect is working fine with IntelliJ and redirects to the path "/" with the title refreshing with the passed in username. I'm lost as to what I am doing wrong.
package com.teamtreehouse.courses;
import com.teamtreehouse.courses.model.CourseIdea;
import com.teamtreehouse.courses.model.CourseIdeaDAO;
import com.teamtreehouse.courses.model.SimpleCourseIdeaDAO;
import spark.ModelAndView;
import spark.template.handlebars.HandlebarsTemplateEngine;
import java.util.HashMap;
import java.util.Map;
import static spark.Spark.*;
/**
* Created by nfleig on 16.07.17.
*/
public class Main {
public static void main(String[] args) {
staticFileLocation("/public");
CourseIdeaDAO dao = new SimpleCourseIdeaDAO(); //This SimpleCourseIeaDAO is not meant for production. Just a prototype. Should be linked to a DB
get("/", (req, res) -> {
Map<String, String> model = new HashMap<>();
model.put("username", req.cookie("username"));
return new ModelAndView(model, "index.hbs");
}, new HandlebarsTemplateEngine());
// Replaces previous post request. This one redirects to main page.
post("/", (req, res) -> {
String username = req.queryParams("username");
res.cookie("username", username);
res.redirect("/");
return null;
});
get("/ideas", (req, res) -> {
Map<String, Object> model = new HashMap<>();
model.put("ideas", dao.findAll());
return new ModelAndView(model, "ideas.hbs");
}, new HandlebarsTemplateEngine());
post("/ideas", (req, res) -> {
String title = req.queryParams("title");
//TODO:nfa - This username is tied to the cookie. Problem: only way to know user is logged in is by cookie
CourseIdea courseIdea = new CourseIdea(title,
req.cookie("username"));
dao.add(courseIdea);
res.redirect("/ideas");
return null;
});
}
}
2 Answers
Seth Kroger
56,414 PointsThe issue is you replaced the proper route, "/sign-in", with "/". Instead of redirecting from /sign-in, it will produce a 404 error because there is no handler for it.
Nelson Fleig
25,764 PointsIt wasn't producing any 404 error in IntelliJ because I changed the form's action to "/" in index.hbs . But without changing the HTML, I would indeed have to leave the route as /sign-in. It is solved now.
Thank you so much for the help!