gpt4 book ai didi

javascript - 意外 token node.js v8.9.4

转载 作者:太空宇宙 更新时间:2023-11-04 03:22:42 25 4
gpt4 key购买 nike

我刚刚开始学习 Node.js (v8.9.4),我创建了一个简单的 Web 服务器。我收到以下语法错误消息。我知道=>运算符是node.js最近添加的,但是我使用的是最新的稳定版本。还有其他人遇到过这个吗?有人对尝试解决此问题有任何建议吗?我尝试运行的 JavaScript 文件位于错误消息下方。

SyntaxError: Unexpected token =>
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:607:28)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:608:3


const http = require('http');

http.createServer(function(req, res) => {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.send('Hello World');
}).listen(3000);

console.log('Server running at http://localhost:3000/');

最佳答案

您遇到了问题:

http.createServer(function(req, res) => {

删除 function 关键字,或删除 =>。只需要两者之一。

(args) => { return do-something-with-args; }

相当于

function(args) { return do-something-with-args; }

箭头函数和旧式函数之间存在差异,这与函数内部 this 的定义有关,但它们对于您的问题并不重要。简而言之,箭头函数中的 this 作用域为声明箭头函数的 block (在本例中为您的模块),而对于旧式 functionthis 的作用域为函数本身。

仅供引用,箭头函数对于 NodeJS 来说并不是特别"new"。它们自 2015 年左右就存在了(我认为是 4.4.5。)

关于javascript - 意外 token node.js v8.9.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48368286/

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