javascript - Express/nodejs 中的参数化路由 url 之后添加静态文件

标签 javascript mysql node.js express

我试图根据 /details 之后包含的两个参数获取详细信息。我传递的参数正在获取 url 中。但我的静态文件夹 /others 添加在 /details/id/others/filenames.js 或 css 之后。所以我没有完美地获得页面 View 。 我尝试在 html 页面中打印传递的 url 数据。但他们也没有表现出来。我的代码中没有遇到问题,因为我是 Nodejs 的新手。

这是 app.js 文件。

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var connection = require('express-myconnection');
var mysql = require('mysql');

var routes = require('./routes/index');
var search = require('./routes/search');
var urlencodedParser = bodyParser.urlencoded({ extended: false })

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/others', express.static('others'));

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//app.use(express.json());       // to support JSON-encoded bodies
//app.use(express.urlencoded());

app.use(
    connection(mysql, {
        host: 'localhost',
        user: 'root',
        password: '',
        port: 3306, //port mysql
        database: 'archive'
    }, 'request')
);

//routes for pages from index.js 
app.get('/', routes.index);
app.get('/details', routes.details);

app.get('/list', routes.list);


//posting the form
app.post('/list', urlencodedParser, function (req, res) {
    //console.log(req.body);
    //res.render('list', {data: req.body});
    req.getConnection(function (err, con) {
        con.query('select * from arc_book WHERE title like "%' + req.body.title + '%" or isbn like "%' + req.body.title + '%" or description like "%' + req.body.title +'%"  order by title asc', function (err, rows) {
            if (err)
                console.log("Error in solution : %s ", err);
            //else
            //    console.log(rows);
            res.render('list', { data: rows });
        });
    });
});
app.get('/details/:book_id/:uploaded_by',function (req, res) {
    req.getConnection(function (err, con) {
        con.query("SELECT * FROM arc_book b,arc_user u where b.uploaded_by=u.id and u.id='" + req.params.uploaded_by + "' and b.id='" + req.params.book_id + "'", function (err, rows) {
            if (err)
                return console.log("Error in solution : %s ", err);
            else {
               // console.log(rows);
                res.render('details', { data: rows });
            }
        });

    });
});




// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;

这里是 HTML 列表文件部分,我从这里生成 URL 以将数据传递到/details 页面。

<div class="col-sm-9" style=" padding-bottom: 20px;">
                    <table id="myTable" class="table-striped table-hover custom-table" cellspacing="0" width="100%">
                        <thead style="background-color: #191D3D; color: #fff; font-weight: 100;">
                            <tr>
                                <th>Title</th>
                                <th>Uploaded BY</th>
                                <th>Upload Date</th>
                                <th class="hidden-xs">Size</th>
                                
                            </tr>
                        </thead>
                        <tbody>
                            <% for(var key in data) { %>
                            <tr>
                                <td><a href="/details/<%= data[key].id %>/<%= data[key].uploaded_by %>" style="color: #000;"><%= data[key].title %></a></td>
                                <td><%= data[key].uploaded_by %></td>
                                <td><%= data[key].upload_date %></td>
                                <td class="hidden-xs"><%= data[key].file_size %> Kb</td>
                                
                            </tr>
                            <% } %>
                        </tbody>
                    </table>
                </div>

最后,这是我试图显示我的数据的详细信息页面。

<% include header.ejs %>


<section class="container-fluid" style="background-color: #ffffff; padding: 0px 0px 50px 0px;">

    <div class="container-fluid">
        <div class="col-sm-12">
            <div class="col-sm-12">
                <p style="color: #000000; font-size: 20px; padding: 15px 0px 20px 0px;"></p>
                <div class="col-sm-3 filter" style="min-height: 500px;" id="filter-div">
                    <p class="filter_head1">AUTHOR</p>
                    <p style="border-top: 3px solid #cdcdcd; position: relative; top: -30px;;"></p>
                    <div class="">
                        <div class="image-wrapper3">
                            <img src="others/uploads/users/client/John-01685456525_avatar04.png">
                        </div>
                        <p class="name_title">
                            <%= data.first_name %>
                        </p>
                        <p class="des_title">
                            Content Maker at Optinfer limited
                            <%= data.first_name %>
                        </p>
                    </div>
                    <div class="" style="margin-top: 50px">
                        <div class="details_title">
                            <p>
                                <b>START </b><span>08:00 AM - 22 Aug, 2017</span>
                            </p>
                            <p>
                                <b>END </b><span>08:00 AM - 22 Dec, 2017</span>
                            </p>
                            <p>
                                <i class="fa fa-map-marker" aria-hidden="true"></i>
                                <span>Dhaka, Bangladesh</span>
                            </p>
                            <p>
                                <i class="fa fa-phone" aria-hidden="true"></i>
                                <span>+88017XXXXXXX</span>
                            </p>
                            <p>
                                <i class="fa fa-envelope" aria-hidden="true"></i>
                                <span>contact@optinfer.com</span>
                            </p>
                        </div>
                    </div>
                </div>



                <div class="col-sm-9" style=" padding-bottom: 20px;">
                    <p class="title_head">HTML Tutotial</p>
                    <article class="article-meta">
                        <div class="image-wrapper2">
                            <img src="others/coveruploads/event/rawa_camera-art-wallpaper-1.jpg">
                        </div>

                        <p>
                            Where does it come from? Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
                        </p>
                        <p>
                            The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
                        </p>
                        <p>
                            The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.
                        </p>
                        <p>
                            There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don't look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn't anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.
                        </p>

                    </article>
                </div>
            </div>
        </div>
    </div>
</section>

</br>

<% include footer.ejs %>

最后,我在尝试请求时在控制台中获得的输出添加到此处

GET /details/86/others/js/dataTables.bootstrap.js 404 0.712 ms - 88

其他文件夹位于根目录中。但它是在细节之后添加的。 我该如何解决这个问题以及如何在 View 页面中显示传递的数据? 预先感谢您的帮助

最佳答案

您的问题是由您的 html 模板中的任何位置包含“others/js/dataTables.bootstrap.js”引起的,您可能指定了一个相对路径,正如您在此处看到的那样。尝试使用“/others/js/dataTables.bootstrap.js”。

关于javascript - Express/nodejs 中的参数化路由 url 之后添加静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45014365/

相关文章:

javascript - typescript : Why does keyof {} have the type never?

mysql - Galera_new_cluster 命令未启动集群

javascript - 在调整窗口大小时将动态值分配给变量 - javascript

mysql - 根据另一个列表的结果查找一个列表

mysql语法错误1064在第194行为多对多关系添加外键

javascript - Nest JS GraphQL “Cannot return null for non-nullable”

node.js - npm -v 更新后也显示旧版本

node.js - 每次在 Elasticsearch 中插入文档时自动增加字段值

javascript - 如何动态更新chrome应用程序的版本号?

javascript - 'React' 指的是一个 UMD 全局,但当前文件是一个模块