0

I'm having trouble with Node JS.

With the Apache/php model, I'm able to make a standalone save.php file (takes a post request, saves to a txt file) without fooling around with the Apache server.

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

In Node, I have server.js started to serve up whatever files I have in /public :

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);

How can I make a save.js file, e.g. /public/test_project1/save.js, that can be executed on an HTML form submission?

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

Is there any way to avoid explicitly defining the app.post()... in server.js every time I make a new js file in /public? I'm looking for an architecture that allows me to create one node server to host various separate project files in /public

1

2 Answers 2

0

First you need to create a endpoint for your post request, then parse form data, a option could be body-parser middleware , finally save the content.

Something like:

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);

Then you make a POST request to /endpoint with myData as input.

Sign up to request clarification or add additional context in comments.

Comments

0

Here's what I came up with - modifying server.js to handle any POST requests within that folder. Is this dangerous?

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);          
        }
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.