2016-01-20 33 views
0

我遇到了Node JS的麻煩。如何使用Node js Express創建獨立的可執行js文件,而無需定義路由?

藉助Apache/php模型,我可以獨立製作一個獨立的save.php文件(接受一個帖子請求,保存到一個txt文件中)而不會與Apache服務器混淆。

<?php file_put_contents ('content.txt' , $_POST['myData']);?> 

在節點,我有server.js開始成爲了我在/公共任何文件:

var express = require('express'); 
var app = express(); 
app.use(express.static('public')); 
app.use(express.static(__dirname + '/public')); 

app.use(function(req,res, next){ 
    if(req.accepts('html')){ 
    res.status(404).sendFile(__dirname+'/public/404.html'); 
    } 
}); 

app.listen(process.env.PORT || 80); 

我怎樣才能讓一個save.js文件,例如/public/test_project1/save.js,可以在HTML表單提交中執行?

var fs = require('fs'); 
fs.writeFile("content.txt", ???post data???) 

有什麼辦法避免明確定義app.post()......在每一次server.js我做出/公衆一個新的js文件?我正在尋找一種架構,允許我創建一個節點服務器來承載/ public中的各個單獨項目文件

+0

[Express Static nodejs]的可能重複(http://stackoverflow.com/questions/7069360/express-static-nodejs) – Jordonias

回答

0

首先,您需要爲您的發佈請求創建端點,然後解析表單數據,選項可能是body-parser中間件,最後保存內容。

喜歡的東西:

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

app.use(bodyparser.urlenconded({extended:true}); // middleware for parse form data 
app.use(express.static('public')); 
app.use(express.static(__dirname + '/public')); 
app.post("/endpoint",function(req,res){ 
//myData is input name 
var content = req.body.myData; 
fs.writeFile("content.txt", content,function(err){ 
    res.end("done"); 
}) 
}) 

app.use(function(req,res, next){ 
    if(req.accepts('html')){ 
    res.status(404).sendFile(__dirname+'/public/404.html'); 
    } 
}); 

app.listen(process.env.PORT || 80); 

然後你做一個POST請求/端點MYDATA的作爲輸入。

0

這是我想出的 - 修改server.js來處理該文件夾內的任何POST請求。這是危險的嗎?

app.post('/:folder/:file',function(req, res){ 
    filepath=__dirname+'/public/'+req.params.folder+'/'+req.params.file; 
    fs.stat(filepath, function(err, stat) { 
     if(err == null) { 
      console.log('File exists'); 
      var anyFile=require(filepath)(req.body); 
      res.redirect(anyFile); 
     } else if(err.code == 'ENOENT') { 
      res.send('File does not exist.'); 
     } else { 
      res.send('Error: '+ err.code);   
     } 
    }); 
}); 
相關問題