Osan
Osan

Reputation: 187

Can Node.js write javascript to the browser along with html?

Here's what I would think works, but doesn't:

res.writeHead(200, {'content-type': 'text/html'});
res.end(
   '<form action="/upload" enctype="multipart/form-data" method="post">'+
   '<input type="text" name="title"><br>'+
   '<input type="file" name="upload" multiple="multiple"><br>'+
   '<input type="submit" value="Upload">'+
   '</form>' +
   '<script type="text/javascript">alert("hi")</script>'
);

What ends up happening is the browser will write the script tag, but doesn't evaluate it as javascript. Can this work, or do I need to send the javascript in its own res.writeHead() prior to the html?

Edit: the actual html that gets written is just

<form action="/upload" enctype="multipart/form-data" method="post"><input name="title" type="text"><br><input name="upload" multiple="multiple" type="file"><br><input value="Upload" type="submit"></form>
<script type="text/javascript">alert("hi")</script>

Thanks

Upvotes: 0

Views: 3548

Answers (1)

Alfred
Alfred

Reputation: 61771

Works just fine for me. I am using expressjs to simplify my work

var express = require('express'),
        app         = express.createServer();

app.get('/', function(req, res){
    res.writeHead(200, {'content-type': 'text/html'});
    res.end(
   '<form action="/upload" enctype="multipart/form-data" method="post">'+
   '<input type="text" name="title"><br>'+
   '<input type="file" name="upload" multiple="multiple"><br>'+
   '<input type="submit" value="Upload">'+
   '</form>' +
   '<script type="text/javascript">alert("hi")</script>'
);
});

app.listen(3000, '127.0.0.1');

enter image description here

Upvotes: 1

Related Questions