节点包含上传.js给了我一个ERR_CONNECTION_REFUSED



我是使用node.js的新手。

我想打电话给另一个.js当服务器页面是/注册时

所以我有我的服务器.js:

const http = require('http')
const port = 80
const ip = 'localhost'
const server = http.createServer((req, res) => {
if (req.url == '/') {
res.end('<h1>Home</h1>');
}
else if (req.url == '/signup') {
require('./upload.js');
}
})
server.listen(port, ip, () => {
console.log(`running http://${ip}:${port}`)
console.log('Press ctrl + c to stop');
})

和上传.js:

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

if (req.url == '/fileupload') {
var form = new formidable.IncomingForm();
form.parse(req, function (err, fields, files) {
var oldpath = files.filetoupload.path;
var newpath = '/' + files.filetoupload.name;
fs.rename(oldpath, newpath, function (err) {
if (err) throw err;
res.write('File uploaded and moved!');
res.end();
});
});
} 
else {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write('<form action="fileupload" method="post" enctype="multipart/form-data">');
res.write('<input type="file" name="filetoupload"><br>');
res.write('<input type="submit">');
res.write('</form>');
return res.end();
}

问题是/注册正在ERR_CONNECTION_REFUSED。

怎么了?有什么想法吗? 谢谢!

问题是你思考nodeJs需要的方式。您不需要文件来调用/执行该文件(尽管它们确实会被执行(。您需要它在当前文件中包含另一个文件的功能。然后执行所需的函数。很像 C 中的 #include。我敦促您阅读本文以了解它在nodejs中的工作原理。

此外,如果您还没有阅读过nodejs中异步编程的概念,则必须了解它 - https://blog.risingstack.com/node-hero-async-programming-in-node-js/

相关内容

最新更新