2015-09-23 18 views
6

Ho seguito di recente un semplice tutorial su come creare un server Express (https://codeforgeek.com/2014/06/express-nodejs-tutorial/).Express Server - Can not POST/

Sto cercando di estendere il codice da questo tutorial in modo che possa rispondere alle richieste di posta. Io voglio fare questo aggiornando un file JSON (che sembra essere pieno di commenti degli utenti '', e poi rerendering a '/'

./server.js:

var express = require('express'); 
var app = express(); 

// routing configuration 
require('./router/main')(app); 

// ejs configuration 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'ejs'); 
app.engine('html', require('ejs').renderFile); 

// run the server 
var server = app.listen(8080, function(){ 
    console.log('Express server listening on port 8080'); 
}); 

. /router/main.js (router):

var fs = require('fs'); 
var ejs = require('ejs') 

module.exports = function(app){ 

    app.get('/', function(req, res){ 
    var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json')); 
    res.render('index.ejs', comments); 
    }); 

    app.post('/', function(req, res){ 
    console.log('here in post'); 
    var name = req.body.name; 
    var message = req.body.message; 
    var newComment = {"name": name, "message": message}; 
    var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json')); 
    comments.push(newComment); 
    fs.writeFileSync(__dirname + '/../comments.json', comments, 'utf8'); 
    //redirect to a 'get' on '/' 
    res.redirect('/'); 
    }); 

    app.get('/about', function(req, res){ 
    res.render('about.html') 
    }); 

} 

./views/index.ejs:

<div> 

    <div> 
    <h1> Joe's Forum </h1> 
    <a href='/about'> (about) </a> 
    </div> 

    <div> 
    <ul> 
    <% comments.forEach(function(comment){ %> 
     <li> 
     <%= comment.name %> : <%= comment.message %> 
     </li> 
    <% }); %> 
    </ul> 
    </div> 

    <h2> Enter a new comment </h2> 

    <form action='/' method="post"> 
    Enter your name: <input type='text' name='name'> <br><br> 
    Enter your message: <input type='textarea' name='message'> <br><br> 
    <input type='submit' value='Submit'> 
    <form> 

</div> 

./comments.json:

{ 
    "comments": [ 
    {"name":"Joe", "message" : "What advantages does Node.js afford the web developer?"}, 
    {"name": "John", "message": "Asynchronous IO helps us to keep our pages responsive even if the server is fetching data"} 
    ] 
} 

Quando si tenta di inviare un nuovo commento dalla mia forma, tutto quello che vedo è questo:

"Impossibile POST /"

Qualcuno può spiegare perché potrei ricevere questo errore? Grazie

+0

si sta facendo qualcosa di vero e proprio no-no. Non dovresti mai usare mai l'API 'Sync' di nodeJS e certamente non nella risposta da un server express. Inoltre, non vi è alcun errore di verifica da nessuna parte, quindi il tuo server sarà molto incline al crash. Puoi mostrare il contenuto di 'comments.json'? – caasjj

+0

Ok abbastanza giusto. Tuttavia, volevo solo "farlo funzionare" come un esercizio in cui appoggiare Express. So che non è un gran bel codice. Una volta che ho ottenuto il "post richiesta", ho intenzione di ripulirlo (ad esempio, iscriviti alle migliori pratiche). Come richiesto, modificherò per includere comments.json. –

+0

Non era affatto una critica, ma solo una cosa che potresti o non potresti sapere. Ora, penso di capire anche perché il tuo codice non funziona bene. Stai facendo 'comments.push' su un' Object' - piuttosto che su un 'Array'. Fammi vedere se riesco a trovare una risposta chiara per te. – caasjj

risposta

3

In realtà ci sono un paio di problemi, ma il principale è che non si dispone di un parser del corpo - il modulo che converte un flusso di nodi nel POST in un req.body. Al momento ho solo familiarità con bodyParser e probabilmente dovresti cercare un po '. Sebbene sia mostrato nella documentazione di Express 4.x, si ottiene un messaggio di deprecazione quando si esegue il server.

L'altro problema è il problema di comments.push. Questo dovrebbe essere comments.comments.push. Le seguenti opere:

router.js:

var fs = require('fs'); 
var ejs = require('ejs') 

module.exports = function(app){ 

    app.get('/', function(req, res){ 
    var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json')); 
    res.render('index.ejs', comments); 
    }); 

    app.post('/', function(req, res){ 
    console.log('here in post'); 
    console.log(req.body) 
    var name = req.body.name; 
    var message = req.body.message; 
    var newComment = {"name": name, "message": message}; 
    var comments = JSON.parse(fs.readFileSync(__dirname + '/../comments.json')); 
    comments.comments.push(newComment); 
    fs.writeFileSync(__dirname + '/../comments.json', JSON.stringify(comments), 'utf8'); 
    //redirect to a 'get' on '/' 
    res.redirect('/'); 
    }); 

    app.get('/about', function(req, res){ 
    res.render('about.html') 
    }); 

} 

e server.js:

var express = require('express'); 
var bodyParser = require('body-parser'); 
var app = express(); 

app.use(bodyParser.urlencoded()) 

// routing configuration 
require('./router/main')(app); 

// ejs configuration 
app.set('views', __dirname + '/views'); 
app.set('view engine', 'ejs'); 
app.engine('html', require('ejs').renderFile); 

// run the server 
var server = app.listen(8080, function(){ 
    console.log('Express server listening on port 8080'); 
}) 
+0

Grazie per la risposta. Quando avrò 15 reputazione, la inviterò. –

+0

Apprezzo questo!Si prega di esaminare il problema dell'analisi del corpo e del middleware in generale, poiché ciò si dimostrerà molto istruttivo su come Express funziona. – caasjj

Problemi correlati