首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >路径必须是字符串和POST localserver 500 internet服务器。

路径必须是字符串和POST localserver 500 internet服务器。
EN

Stack Overflow用户
提问于 2017-11-24 21:13:18
回答 1查看 150关注 0票数 0

我试图做的是简单的培训服务器应用程序与CRUD功能。我成功地编辑或删除了已经存在的用户,但仍然试图解决如何实际创建和添加现有的users.json文件。我肯定我遗漏了什么。

完整目录的Git:https://gitlab.com/alexgnatrow/practice-nodejs

这是主要的index.js。

代码语言:javascript
复制
    const express = require('express');
    const app = express();
    const path = require('path');

    const fs = require('fs');
    const _ = require('lodash');
    const engines = require('consolidate');
const bodyParser = require('body-parser'); 


let users = [];

function getUser(username) {
    let user = JSON.parse(fs.readFileSync(getUserFilePath(username), {encoding: 'utf8'}));
    user.nickname = user.name.toLowerCase().replace(/\s/ig, '');

    return user
}

function getUserFilePath(username) {
    return `${path.join(__dirname, 'users', username)}.json`
}

function createUser(username, data){
    let fp = getUserFilePath(username);
    let string =  JSON.stringify(data, null , 2);
    console.log(string);
    fs.writeFileSync(fp, string , {encoding: 'utf8'})
}

function saveUser(username, data) {
    let fp = getUserFilePath(username);
    fs.unlinkSync(fp);
    console.log(data);
    fs.writeFileSync(fp, JSON.stringify(data, null, 2), {encoding: 'utf8'})
}

function verifyUser(req, res, next) {
    let username = req.params.username;
    let fp = getUserFilePath(username);

    fs.exists(fp, yes => {
        if (yes) {
            next()
        } else {
            res.redirect('/error/' + username)
        }
    })
}

app.engine('hbs', engines.handlebars);

app.set('views', './views');
app.set('view engine', 'hbs');


app.use(express.static('public')); //example of serve static files
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json()); // Body parser use JSON data

app.get('/', (req, res) => {
    fs.readdir('users', (err, files) => {
      if(err|| files==="favicon.ico"){console.log('there is no need to create a fucking favicon');}
        files = _.filter(files, file => !file.startsWith('.'));
        users = _.map(files, file => getUser(file.replace(/\.json/ig, '')));
        res.render('index', {users})
    });
});

app.get('*.json', (req, res) => res.download('./users/' + req.path));
app.get('/error/:username', (req, res) => res.status(404).send(`No user named ${req.params.username} found`));
app.get('/data/:username', (req, res) => {
    res.header("Content-Type", 'application/json');
    res.send(JSON.stringify(getUser(req.params.username), null, 4));
});

app.all('/:username', function(req, res, next) {
    console.log(req.method, 'for', req.params.username);
    next()
});

app.get('/:username', verifyUser, function(req, res) {
    const user = getUser(req.params.username);
    res.render('user', {user, address: user.location})
});

app.post('/', (req,res)  => {
    createUser(req.params.name, req.body);
    console.log(req.body);
    res.end()
});

app.put('/:username', function(req, res) {
    saveUser(req.params.username, req.body);
    res.end()
});

app.delete('/:username', function(req, res) {
    fs.unlinkSync(getUserFilePath(req.params.username)); // delete the file
    res.sendStatus(200)
});

const server = app.listen(3000, function() {
    console.log('Server running at http://localhost:' + server.address().port)
});      

我尝试添加一个用户的index.hbs和html页面:

代码语言:javascript
复制
const express = require('express');
const app = express();
const path = require('path');

const fs = require('fs');
const _ = require('lodash');
const engines = require('consolidate');
const bodyParser = require('body-parser');


let users = [];

function getUser(username) {
    let user = JSON.parse(fs.readFileSync(getUserFilePath(username), {encoding: 'utf8'}));
    user.nickname = user.name.toLowerCase().replace(/\s/ig, '');

    return user
}

function getUserFilePath(username) {
    return `${path.join(__dirname, 'users', username)}.json`
}

function createUser(username, data){
    let fp = getUserFilePath(username);
    let string =  JSON.stringify(data, null , 2);
    console.log(string);
    fs.writeFileSync(fp, string , {encoding: 'utf8'})
}

function saveUser(username, data) {
    let fp = getUserFilePath(username);
    fs.unlinkSync(fp);
    console.log(data);
    fs.writeFileSync(fp, JSON.stringify(data, null, 2), {encoding: 'utf8'})
}

function verifyUser(req, res, next) {
    let username = req.params.username;
    let fp = getUserFilePath(username);

    fs.exists(fp, yes => {
        if (yes) {
            next()
        } else {
            res.redirect('/error/' + username)
        }
    })
}

app.engine('hbs', engines.handlebars);

app.set('views', './views');
app.set('view engine', 'hbs');


app.use(express.static('public')); //example of serve static files
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json()); // Body parser use JSON data

app.get('/', (req, res) => {
    fs.readdir('users', (err, files) => {
      if(err|| files==="favicon.ico"){console.log('there is no need to create a favicon');}
        files = _.filter(files, file => !file.startsWith('.'));
        users = _.map(files, file => getUser(file.replace(/\.json/ig, '')));
        res.render('index', {users})
    });
});

app.get('*.json', (req, res) => res.download('./users/' + req.path));
app.get('/error/:username', (req, res) => res.status(404).send(`No user named ${req.params.username} found`));
app.get('/data/:username', (req, res) => {
    res.header("Content-Type", 'application/json');
    res.send(JSON.stringify(getUser(req.params.username), null, 4));
});

app.all('/:username', function(req, res, next) {
    console.log(req.method, 'for', req.params.username);
    next()
});

app.get('/:username', verifyUser, function(req, res) {
    const user = getUser(req.params.username);
    res.render('user', {user, address: user.location})
});

app.post('/', (req,res)  => {
    createUser(req.params.name, req.body);
    console.log(req.body);
    res.end()
});

app.put('/:username', function(req, res) {
    saveUser(req.params.username, req.body);
    res.end()
});

app.delete('/:username', function(req, res) {
    fs.unlinkSync(getUserFilePath(req.params.username)); // delete the file
    res.sendStatus(200)
});

const server = app.listen(3000, function() {
    console.log('Server running at http://localhost:' + server.address().port)
});

错误日志

代码语言:javascript
复制
Server running at http://localhost:3000
TypeError: Path must be a string. Received undefined
    at assertPath (path.js:28:11)
    at Object.join (path.js:501:7)
    at getUserFilePath (C:\Users\Лёша\jsDir\practice-nodejs\index.js:21:20)
    at createUser (C:\Users\Лёша\jsDir\practice-nodejs\index.js:25:14)
    at app.post (C:\Users\Лёша\jsDir\practice-nodejs\index.js:88:5)
    at Layer.handle [as handle_request] (C:\Users\Лёша\jsDir\practice-nodejs\nod
e_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\express\lib\router
\route.js:137:13)
    at Route.dispatch (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\express\
lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\Лёша\jsDir\practice-nodejs\nod
e_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Лёша\jsDir\practice-nodejs\node_modules\express\lib\router\index
.js:281:22
    at Function.process_params (C:\Users\Лёша\jsDir\practice-nodejs\node_modules
\express\lib\router\index.js:335:12)
    at next (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\express\lib\router
\index.js:275:10)
    at C:\Users\Лёша\jsDir\practice-nodejs\node_modules\body-parser\lib\read.js:
130:5
    at invokeCallback (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\raw-body
\index.js:224:16)
    at done (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\raw-body\index.js:
213:7)
    at IncomingMessage.onEnd (C:\Users\Лёша\jsDir\practice-nodejs\node_modules\r
aw-body\index.js:273:7)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-24 21:40:16

在这段代码中,req.params.name是未定义的:

代码语言:javascript
复制
app.post('/', (req,res)  => {
    createUser(req.params.name, req.body);
    console.log(req.body);
    res.end()
});

are the parameters passed to a route。(例如,/:name)

也许您是指req.body ( POST有效负载中的JSON主体)?

代码语言:javascript
复制
app.post('/', (req,res)  => {
    createUser(req.body.name, req.body);
    console.log(req.body);
    res.end()
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47480091

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档