首页 文章

使用express和body-parser设置服务器

提问于
浏览
0

我想用Express和Body-parser设置服务器 . 我做了:

npm init -y

在我的项目目录中 .

然后:

npm install express body-parser --save

结果:package.json文件如下

{
  "name": "myapp",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.18.2",
    "express": "^4.16.2"
  }
}

然后在那里创建了index.js文件,我在这里放了这段代码:

const express = require(‘express’);
const bodyParser = require(‘body-parser’);
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(3000, () => console.log(‘Webhook server is listening, port 3000’));

并运行节点index.js

我收到了这个错误:

(function(exports,require,module,__ filename,__ name){const express = require('express'); ^ SyntaxError:在Object.runInThisContext(vm . )的createScript(vm.js:80:10)处出现无效或意外的标记 . 在Module.load(module.js:556:32)的Object.Module._extensions..js(module.js:654:10)的Module._compile(module.js:607:28)处的模块:139:10)在tryModuleLoad(module.js:499:12)的Function.Module._load(module.js:491:3)处,在Function.Module.runMain(module.js:684:10)启动时(bootstrap_node.js:187: 16)在bootstrap_node.js:608:3

有什么问题?我不明白,这是我第一次使用node.js

2 回答

  • 2

    更改为单引号 ' 并且它将起作用:

    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.listen(3000, () => console.log('Webhook server is listening, port 3000'));
    

    通过控制台运行:

    $ node index.js
    Webhook server is listening, port 3000
    
  • 1

    您似乎使用了一些文本处理器(例如MS Word)而不是更简单的文本编辑器(例如Windows上可用的记事本或写字板)或专门用于程序员的编辑器(例如Nodepad或Atom) . 因为文本处理器没有意识到你正在编写一个编程代码,他们认为你正在编写一篇普通的文章,以供人类阅读,所以他们会自动将 straight quotes ' and ' 替换为 smart quotes ‘ and ’ ,这些文章被视为node.js根本不是引号 . 所以单引号的相同代码实际上工作正常:

    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    app.listen(3000, () => console.log('Webhook server is listening, port 3000'));
    

    我强烈建议使用针对程序员的文本编辑器,尤其是Atom,它本身是在node.js中设计的,用于在node.js和相关技术(html,json,CSS)中编写应用程序 . 但是,如果您继续使用MS Word(我的版本是2010),则可以通过以下菜单将自动更正选项转换为智能引号:

    文件↦选项↦校对↦自动更正选项...↦自动套用格式↦替换

    并且☑❏取消选中第一个选项 .

相关问题