Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/419.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/33.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 无法建立cookie会话_Javascript_Node.js_Authentication_Cookie Session - Fatal编程技术网

Javascript 无法建立cookie会话

Javascript 无法建立cookie会话,javascript,node.js,authentication,cookie-session,Javascript,Node.js,Authentication,Cookie Session,我目前正在使用javascript做一个用户注册界面。但是,我无法建立cookie会话 在本地主机网络中启动后,会提示此消息-->无法访问站点。本地主机拒绝连接 我已重新插入cookie会话包,但它仍然不起作用 有没有办法让它发挥作用 以下是来自终端的错误消息: (节点:7978)未处理的PromisejectionWarning:TypeError:无法读取未定义的属性“id” 在/Users/gabrieswee/Desktop/Desktop Folders/Courses/Javascr

我目前正在使用javascript做一个用户注册界面。但是,我无法建立cookie会话

在本地主机网络中启动后,会提示此消息-->无法访问站点。本地主机拒绝连接

我已重新插入cookie会话包,但它仍然不起作用

有没有办法让它发挥作用

以下是来自终端的错误消息: (节点:7978)未处理的PromisejectionWarning:TypeError:无法读取未定义的属性“id” 在/Users/gabrieswee/Desktop/Desktop Folders/Courses/Javascript/ecomm/index.js:58:29 (节点:7978)未处理的PromisejectionWarning:未处理的承诺拒绝。此错误源于在没有catch块的异步函数中抛出,或者拒绝未使用.catch()处理的承诺。要在未处理的承诺拒绝时终止节点进程,请使用CLI标志
--unhandled rejections=strict
(请参阅)。(拒绝id:1) (节点:7978)[DEP0018]弃用警告:未处理的承诺拒绝已弃用。将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程

这是我的语法

index.js

const express = require("express");
const bodyParser = require("body-parser");
const cookieSession = require("cookie-session");
const usersRepo = require("./repository/users");

const app = express();

//NOTE: Middleware: To automatically body parse the data

app.use(bodyParser.urlencoded({
    extended: true
}));

//NOTE: Middleware: Cookie Session

app.use(
    cookieSession({
        name: "session",
        keys: ["lucky6226"]
    })
);

//NOTE: User Sign Up
app.get("/", (req, res) => {
    res.send(`
    <div>
    Your id is:${req.session.userId}
    <form method ="POST">
    <input name ="email" placeholder="email" />
    <input name ="password" placeholder="password" />
    <input name ="passwordConfirmation" placeholder="password confirmation" />
    <button>Sign Up</button>
    </form>
    </div>
    `);
});

//NOTE: Validating User Email and Password

app.post("/", async (req, res) => {
    const {
        email,
        password,
        passwordConfirmation
    } = req.body;

    const existingUser = await usersRepo.getOneBy({
        email
    });

    if (existingUser) {
        return res.send("Email in use");
    }

    if (password !== passwordConfirmation) {
        return res.send("Password must match");
    }

    //NOTE: Create users in the user repository
    const user = await usersRepo.create({
        email,
        password
    });

    //NOTE: Store ID in the cookie. Use 3rd party package for Cookies --> npm install cookie-session
    req.session.userId = user.id; //Add by cookie session

    res.send("Account Created !!!");
});

//NOTE: HTTP Request
app.listen(3000, () => {
    console.log("Connection established successfully");
});

问题在于,在
UsersRepository
create
函数中,您没有返回创建的用户,因此:

//注意:在用户存储库中创建用户
const user=wait usersRepo.create({
电子邮件,
密码
});
用户
将始终是
未定义的
,当您调用下一行时

req.session.userId=user.id

该错误被抛出

要解决此问题,请执行以下操作:

异步创建(attrs){ attrs.id=this.randomId(); const records=wait this.getAll(); 记录推送(attrs); 等待这一点。书面记录; 返回属性//
const fs = require("fs");
const crypto = require("crypto");

class UsersRepository {

constructor(filename) {
    if (!filename) {
        throw new Error("Creating a repository requires a filename");
    }

    this.filename = filename;

    try {
        //NOTE: Check to see if the file exist
        fs.accessSync(this.filename);
    } catch (err) {
        //NOTE: if file do not exists, create the file
        fs.writeFileSync(this.filename, "[]");
    }
}

async getAll() {
    return JSON.parse(
        await fs.promises.readFile(this.filename, {
            encoding: "utf8"
        })
    );
}

async create(attrs) {
    attrs.id = this.randomId();
    const records = await this.getAll();
    records.push(attrs);
    await this.writeAll(records);
}



async writeAll(records) {
    // NOTE: Write the updated 'records' array back to this.filename
    await fs.promises.writeFile(
        this.filename,
        JSON.stringify(records, null, 2)
    );
}



randomId() {
    return crypto.randomBytes(4).toString("hex");
}



async getOne(id) {
    const records = await this.getAll();
    return records.find(record => record.id === id);
}



async delete(id) {
    const records = await this.getAll();
    //NOTE: Return true if ID is not the same

    const filteredRecords = records.filter(record => record.id !== id);
    await this.writeAll(filteredRecords);
}



async update(id, attrs) {

    const records = await this.getAll();
    const record = records.find(record => record.id === id);

    if (!record) {
        throw new Error(`Record with id ${id} is not found`);
    }

    //NOTE: Assign attrs {password} (attributes) into the record {email}
    Object.assign(record, attrs);

    //NOTE: Outcome --> record === {email: 'test@test.com', password: 'mypassword'}
    await this.writeAll(records);

}



async getOneBy(filters) {

    const records = await this.getAll();
    //NOTE: outer for of loop --> looping through an array
    for (let record of records) {
        let found = true;
        //NOTE: inner for in loop --> search an object

        for (let key in filters) {
            if (record[key] !== filters[key]) {
                found = false;
            }
        }

        if (found === true) {
            return record;
        }
    }

}

//NOTE: File export

module.exports = new UsersRepository("users.json");