javascript - JSON 服务器路由器

标签 javascript json polymer web-component

我正在尝试让 polymer 网页登录正常工作,但似乎不能,因为 app.js 无法读取文件本身中定义的 JSON 数据库。我上传了一张屏幕截图,展示了我的文件夹和文件在 Visual Studio Code 中的分层情况。我使用 Windows 10 NT 操作系统和 Git Bash 来运行我的命令。

这是 GIT BASH 错误

Rhino@DESKTOP-NB42TJJ MINGW64 /c/users/rhino/documents/work/personal/polymer-project $ node demo-server/app.js JSON Server is runnning TypeError: Cannot read property 'users' of undefined at C:\users\rhino\documents\work\personal\polymer-project\demo-server\app.js:34:33 at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5) at next (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\route.js:131:13) at Route.dispatch (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\route.js:112:3) at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5) at C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:277:22 at Function.process_params (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:330:12) at next (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:271:10) at C:\users\rhino\documents\work\personal\polymer-project\demo-server\app.js:29:9 at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5)

这是我的 app.js 文件

    var express = require("../node_modules/express");
    var app = express();
    var path    = require("path");

    var jsonServer = require("../node_modules/json-server");
    var server = jsonServer.create();
    var router = jsonServer.router('db.json');


    //Authentication Libraries  -  Start
    var cookieParser = require('../node_modules/cookie-parser');
    var session = require('../node_modules/express-session');
    //Authentication Libraries - End

    server.use(cookieParser("security", {"path": "/"}));
    app.use(cookieParser("security", {"path": "/"}));

    server.use(function(req, res, next) {
    res.setHeader("Access

-Control-Allow-Origin", "http://localhost:8080");
    res.setHeader("Access-Control-Allow-Credentials", "true");
    res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT,   OPTIONS");
    res.setHeader("Access-Control-Expose-Headers","Access-Control-Allow-Origin");
    res.setHeader("Access-Control-Allow-Headers", 
    "X-Custom-Header,X-Requested-With,X-Prototype-Version,Content-Type,Cache-      Control,Pragma,Origin,content-type");

    if (!req.signedCookies.usersession && req._parsedUrl.pathname !=    "/auth/login" && req.method != "OPTIONS") {
        res.redirect('http://localhost:8080/app/pages/auth/auth.html');
     }else{
        next();
    }
});

    server.post('/auth/login', function(req, res){
    var users = router.db.object.users;
    var username = req.query.username;
    var password = req.query.password;
    for(var i=0;i<=users.length -1;i++){
        if(users[i].username == username && users[i].password == password) {
            res.cookie('usersession', users[i].id, {maxAge: 9000000,    httpOnly: false, signed: true});
            res.send(JSON.stringify({success: true}));
            return;
        }
    }
    res.send(JSON.stringify({ success: false, error: 'Wrong username or password' }));
});

app.get('/', function(req, res){
    if (!req.signedCookies.usersession) {
        res.redirect('app/pages/auth/auth.html');
    }else{
        res.sendFile(path.join(__dirname+'/../app/index.html'));
    }
});

app.get('/auth/logout', function(req, res){
    res.clearCookie('usersession');
    res.redirect('/app/pages/auth/auth.html');
});
/*app.get('/', function(req, res){
    res.sendFile(path.join(__dirname+'/../app/index.html'));
});
*/

app.use(express.static(path.join(__dirname, '../')));
var http = require('http').Server(app);
http.listen(8080);

server.use(jsonServer.defaults); //logger, static and cors middlewares
server.use(router); //Mount router on '/'
server.listen(5000, function () {
    console.log('JSON Server is runnning')
});

Picture of Visual Studio Code project folder structure

最佳答案

您可能需要在代码中添加如下中间件:

var jsonServer   = require('../node_modules/json-server');
var server       = jsonServer.create();
var router       = jsonServer.router('db.json');
var middlewares  = jsonServer.defaults(); //<--- new line

然后在你的 server.use(jsonServer.defaults);//logger、static和cors中间件,注入(inject)中间件如图:

server.use(middlewares); //logger, static and cors middleware

关于javascript - JSON 服务器路由器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37651683/

相关文章:

javascript - Angular2 ng2-auto-complete 实现问题

javascript - Express Nodejs Web 服务中的服务器响应为空

java - 如何使用 Gson 反序列化嵌套接口(interface)类型

javascript - 如何在 JavaScript 中将 JSON 转换为 YAML

javascript - 如何显示铁列表中最后可见的项目?

html - polymer :将 <paper-item> 包裹在自己的元素中

javascript - JavaScript 如何创建与 DOM 元素的单向数据绑定(bind)?

javascript - 如何在javascript/jquery中拼接数组中的值?

javascript - 如何解决 JS 库中 document.getElementById() 的使用

java - 应为 BEGIN_OBJECT,但经过改造后为 BEGIN_ARRAY