我正在用纯节点JS编写一个小表单(我不想要框架,因为我正在练习基础知识以了解它是如何“在引擎盖下”工作的)。
我编写下面的代码是为了将我的POST请求中的数据放到一个我console.log的对象中。
现在我正在尝试在html页面“contact-success.html”中使用它。 我的主要问题是,我没有设法使这些信息在我的HTML上可用。 我试着把它当作常量通过,但什么也没发生。 也许有人会看到我错过了什么? ;)
const server = http.createServer(function(req, res){
console.log('Request was made at ' + req.url)
if(req.url === '/' || req.url === '/home'){
// home page
res.writeHead(200, {'Content-type': 'text/html'})
fs.createReadStream(__dirname + '/html_files/index.html').pipe(res)
} else if(req.url === '/contact'){
// create a if statement to manage the post request (not sure about this part but let's try)
if(req.method === 'POST'){
// we state that body is empty
let body = ''
// on event 'data' a chunk of data is sent to body and stringified
req.on('data', chunk => {
body += chunk.toString()
//on the end of stream, we parse the body and console,log it
req.on('end', () => {
console.log(parse(body))
const contactData = parse(body)
// trying to redirect to contact-successafter posting
res.writeHead(200, {'Content-type': 'text/html'})
fs.createReadStream(__dirname + '/html_files/contact-success.html').pipe(res)
})
})
我可以毫无问题地在控制台记录contactData对象,但似乎无法访问它。
使用模板引擎而不是静态文件。 很多都是可用的。
它们提供了将数据传递到文档中的机制,例如:
const filename = __dirname + '/html_files/contact-success.html';
const html = nunjucks.render(filename, contactData);
如果您使用Express,这将会更容易,Express支持模板引擎,内置和API,这些API使得读取POST数据和为不同URL路由的处理要比您编写的代码简单得多(它重新发明了一堆轮子)。