我正在尝试在服务器端使用 Spark 创建 SPA。 这是我的 App.java:
package com.farot;
import java.util.HashMap;
import java.util.UUID;
import java.net.URL;
import java.net.URISyntaxException;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.nio.charset.Charset;
import java.io.IOException;
import com.google.gson.Gson;
import static spark.Spark.*;
import com.farot.utils.Path;
import com.farot.controllers.UserController;
import com.farot.controllers.AccountController;
import com.farot.controllers.MapController;
public class App
{
private static Gson gson = new Gson();
private static String renderIndex() {
try {
URL url = App.class.getResource("index.html");
return new String(Files.readAllBytes(Paths.get(url.toURI())), Charset.defaultCharset());
} catch (IOException | URISyntaxException e) {
System.out.println(e.getMessage());
}
return null;
}
public static void main( String[] args )
{
staticFiles.location("/public");
before((req, res) -> {
String path = req.pathInfo();
if (path.endsWith("/"))
res.redirect(path.substring(0, path.length() - 1));
});
// Site pages
get("/", "text/html", (req, res) -> renderIndex());
get("/login", "text/html", (req, res) -> renderIndex());
post(Path.Web.api.Account.DEFAULT, (req, res) -> {
return AccountController.create(req, res);
}, gson::toJson);
}
}
Path.Web.api.Account.DEFAULT 处的 POST 请求按预期工作,但/login 处的请求返回 404。可能出了什么问题? index.html 的路径是/resources/public/index.html。
最佳答案
问题出在函数 renderIndex()
中。使用正确的资源路径(即 /public/index.html
)后,变量 url
不再为空,但根据您在评论中所说的,这很奇怪( jar:file:/home/gorrtack/workspace/Farot/target/Farot-1.0-SNAPSHOT-jar-with-dependcies.jar!/public/index.html
),带有没有有效的路径。
当Paths.get()
尝试解析此路径时,它会失败并抛出NoSuchFileException
(这是一个IOException
)。然后,您在 catch
block 中捕获它,并返回 null。返回 null 是错误的,这就是您收到错误 404 的原因。
所以你需要:
- 更改项目结构中的某些内容,使
index.html
的路径正确。那么您将避免这种情况下的问题。 - 正确处理异常,意味着 - 不返回 null。决定在这些情况下您想要做什么,然后,如果您愿意,您仍然可以向客户端提供正常的错误消息和/或使用
request.status()
API 或任何 any other response APIs自行设置回复状态。
关于Java、Spark,返回index.html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44257072/