【问题标题】:SyntaxError: function statements require a function nameSyntaxError:函数语句需要函数名
【发布时间】:2021-04-07 15:07:24
【问题描述】:

这是我使用 Node express 和 EJS 创建待办事项列表网站的代码。 这里我在我的 app.js 中导出 date.js 文件来获取当前日期。

这是我的 app.js:

const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");

const app = express();

let items= ["Buy Food","Cook Food","Eat Food"];
let workItems=[];

app.use(bodyParser.urlencoded({extended:true}));
app.use(express.static("public"));

app.set('view engine', 'ejs');

app.get("/", function(req, res) {
  let day=date();
  res.render("list", {
    ListTitle: day,
    newListItems:items
  });
});

app.get("/work",function(req,res){
  res.render("list", {
    ListTitle: "Work List",
    newListItems:workItems
  });
});

app.post("/work",function(req,res){
  let item=req.body.newItem;
  workItems.push(item);
  res.redirect("/");
});

app.post("/",function(req,res){
  let item=req.body.newItem;
  if(req.body.list==="Work"){
    workItems.push(item);
    res.redirect("/work");
  }else{
    item.push(item);
    res.redirect("/");
  }
});

app.listen(3000, function() {
  console.log("server is up and running at port 3000");
});

当我尝试在我的超级终端中运行它时,它会抛出一个错误:SyntaxError: function statements require a function name

如果我不导出 date.js 文件,而是在 app.js 中写入 date.js 文件的函数 getDate() 的内容,它工作正常。这意味着此行正在生成错误

const date = require(__dirname + "/date.js");

根据我的说法,错误出在这一行或 date.js 文件中。但我无法找出问题所在。

这是我的 date.js 文件:

module.exports= getDate;

function getDate()
{
  let today = new Date();

  let options = {
    weekday:"long",
    day:"numeric",
    month:"long"
  };
  let day = today.toLocaleDateString("en-US", options);
  return day;
}

谁能帮我解决这个问题?

附:这个待办事项列表网络应用程序是 angela Yu 网络开发课程的一部分。我按照课程中给出的相同说明进行操作,但仍然出现此错误。

Here is the error message:

【问题讨论】:

  • 试试const date = require("./date.js");
  • 当您将function() { ... } 放在需要语句而不是表达式的位置时,就会发生该错误。我看不出它是如何来自您发布的任何代码的。
  • 感谢您回复@ChrisG。我试过这个const date = require("./date.js"); 但这条线也给了我同样的错误

标签: javascript node.js express node-modules web-deployment


【解决方案1】:

不要使用__dirname 访问getDate 模块,而是尝试提供完整的相对路径。我不确定你的项目结构是什么样的,但如果app.jsdate.js 在同一个目录中,请写const date = require("./date.js")

【讨论】:

  • 感谢您回复@Gavi Schneider。我也尝试给出完整路径,但它给了我同样的错误。
猜你喜欢
  • 2021-01-11
  • 1970-01-01
  • 2011-12-26
  • 2017-02-16
  • 1970-01-01
  • 1970-01-01
  • 2015-06-22
  • 2018-02-19
  • 1970-01-01
相关资源
最近更新 更多