gpt4 book ai didi

node.js - 具有多个文件的简单 nodejs 示例

转载 作者:搜寻专家 更新时间:2023-11-01 00:38:10 24 4
gpt4 key购买 nike

我在 NodeJS 上写了一个非常简单的项目。我想与其他语言编程示例相似,例如java。所以我做了:server.js、main.js 和模块 (calc.js)。这是他们的代码:

文件 server.js

var main = require('./main');

var http = require('http');
http.createServer(function(req, res){
main.main(req, res);
}).listen(8080, '127.0.0.1');
console.log('Server running at http://127.0.0.1:8080/');

文件 main.js

var calc = require('./calc');

exports.main = function(req, res){
var a = 5;
var b = 9;
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(calc.Plus(a,b));
res.end(calc.Minus(a,b));
};

文件 calc.js

(function(){
module.exports.Plus = function(a, b){
return a+b;
};

module.exports.Minus = function(a, b){
return a-b;
};
}());

我在我的服务器上运行它,但出现错误:

Server running at http://127.0.0.1:8080/ _http_outgoing.js:558 throw new TypeError('First argument must be a string or Buffer'); ^

TypeError: First argument must be a string or Buffer at ServerResponse.OutgoingMessage.end (_http_outgoing.js:558:11) at Object.exports.main (D:\workspace\FirstNodeJS\main.js:7:6) at Server. (D:\workspace\FirstNodeJS\server.js:5:7) at emitTwo (events.js:106:13) at Server.emit (events.js:191:7) at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:546:12) at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)

我只是 NodeJS 的新手。

最佳答案

res.end() 期望第一个参数是字符串或缓冲区。您正在传递一个数字。这就是文档中描述的方式 here .

你可以这样做:

res.end(calc.Plus(a,b).toString());

此外,对于给定的响应,您只能调用一次 res.end()。如果你想发送多个东西作为响应的一部分,你可以在使用 res.end() 之前将它们全部组合成一个字符串,或者你可以调用 res.write() 多次,然后用 res.end() 结束。

关于node.js - 具有多个文件的简单 nodejs 示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44253647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com