使用zig语言制作简单博客网站(二)前端首页初步搭建

167 阅读1分钟

博客我们使用前后端分离形式开发,开发完成后再合并在一起(直接用httpz代理前端,不再单独使用Nginx代理前端)\

html页面准备

我已事先写好了一份博客首页的html,请自行下载 博客html ,解压后用vscode打开,vscode建议安装上Live Server扩展插件,打开index.html,点击vscode右下角Go Live按钮可在浏览器查看博客首页效果,如下图
Live Server Go Live 博客首页效果

前后端联调

前端集成zeptojs(轻量级jQuery替代品)用于发送请求

  • zeptojs地址: zeptojs.devjs.cn/

  • 下载zepto.js并引入到前端项目index.html中并进行测试,如图 引入zepto.js

  • 编写zig后端测试api

// 测试api路由
// 博客首页文章列表
router.get("/api/index/articles", &getIndexArticles);


// 返回文章列表函数
fn getIndexArticles(req: *httpz.Request, res: *httpz.Response) !void {
    _ = req;
    res.status = 200;
    try res.json(.{ .code = 200, .msg = "ok", .data = .{
        .{
            .id = 1,
            .title = "Article1",
            .descriptionion = "Article1 Article1",
            .created_at = "2024-01-01 00:00:00",
            .updated_at = "2024-01-01 00:00:00",
        },
        .{
            .id = 1,
            .title = "Article2",
            .description = "Article2 Article2",
            .created_at = "2024-01-01 00:00:00",
            .updated_at = "2024-01-01 00:00:00",
        },
        .{
            .id = 1,
            .title = "Article3",
            .description = "Article3 Article3",
            .created_at = "2024-01-01 00:00:00",
            .updated_at = "2024-01-01 00:00:00",
        },
    } }, .{});
}
  • 后端启用跨域
    var server = try httpz.Server().init(allocator, .{
        .port = 5588,
        // 跨域设置
        .cors = .{
            .origin = "*",
            .methods = "GET, POST, PUT, DELETE, OPTIONS, PATCH",
            .headers = "*",
        },
    });
  • 编写前端代码展示测试效果
            Zepto(function ($) {
                // alert('Ready to Zepto!');

                // 发送请求,获取首页文章列表
                $.ajax({
                    url: 'http://localhost:5588/api/index/articles',
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        console.log(data);

                    },
                    error: function (err) {
                        console.log(err);
                    }
                })
            })
  • 效果