节点即使已安装也无法识别快递

时间:2019-03-12 03:23:39

标签: node.js express mongoose import babel-preset-env

以前有效的方法不再有效,我对如何解决此问题感到沮丧。我在Mac上运行,并且具有以下版本: 节点:v10.14.1 npm:6.9.0 快递:^ 4.16.4 @ angular / cli:^ 7.3.3 babel-preset-env:^ 1.7.0

即使安装了Express和babel-preset-env,我仍收到以下错误消息:

import express from 'express';
       ^^^^^^^

SyntaxError: Unexpected identifier

这是我在server.js文件中所拥有的:

import express from 'express';
import path from 'path';
import bodyParser from 'body-parser';
import logger from 'morgan';
import mongoose from 'mongoose';
import SourceMapSupport from 'source-map-support';
import cors from 'cors';

// import routes
import weddingRoutes from './routes/wedding.server.route';

// define our app using express
const app = express();

// allow-cors
app.use(function(req,res,next){
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
})
// configure app
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));

// var cors = require('cors');
app.use(cors());

// set the port
const port = process.env.PORT || 3001;

// connect to database
var mongoDB = 'mongodb://127.0.0.1/wedding-website-app';

mongoose.connect(mongoDB, {
  useNewUrlParser: true
});

mongoose.Promise = global.Promise;

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

// add Source Map Support
SourceMapSupport.install();

app.use('/api', weddingRoutes);

app.get('/', (req,res) => {
  return res.send('Api working');
})

// catch 404
app.use((req, res, next) => {
  res.status(404).send('<h2 align=center>Page Not Found!</h2>');
});

// start the server
app.listen(port,() => {
   console.log(`App Server Listening at ${port}`);
});

2 个答案:

答案 0 :(得分:0)

我尝试了您的代码,并显示了您描述的错误,直到我安装了babel-node:

sudo npm install -g @babel/node

然后使用:

babel-node server.js

有关babel-node的更多信息,请在此处查看:babel-node

答案 1 :(得分:0)

const express = require('express');
const path = require('path');

,其他所有内容都应分配给node.js中的变量 另请参阅:https://expressjs.com/en/starter/generator.html 并使用生成器将一切内置。