Uncaught SyntaxError:意外的令牌<,Angular 6试图连接到节点server.js

时间:2018-07-24 21:21:41

标签: json node.js express google-maps-api-3 angular6

我正在使用Angular6,尝试通过Google Map API提供json数据,以使用Node.jsMongoDB进行ajax调用,我有一种在Google Map上放置标记的表单使用api,我正在尝试设置节点js以接收json数据,以便不将其存储在本地存储中,我正在遵循以下教程尝试设置Node.js与{{1 }}并存储位置。

使用express:“ ^ 4.16.3”,express:“ ^ 3.1.1”,

我已经创建了包含所有相关文件的dist文件夹,还创建了带有route文件夹和api.js的服务器文件夹,还有我的server.js,我想我已经准备就绪,但是我一直当我在本地主机3000上运行该错误时,在控制台中收到此错误 this is the error that is showing up in my google chrome console

当我运行http://localhost:3000/api时,它会显示文本“ api有效”

这是我的Server.js

mongodb

这是我的api.js

// Get dependencies
const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

// Get our API routes
const api = require('./server/routes/api');

const app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/mapit/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));

这是我dist文件夹中的index.html

const express = require('express');
const router = express.Router();

/* GET api listing. */
router.get('/', (req, res) => {
  res.send('api works');
});

module.exports = router;

3 个答案:

答案 0 :(得分:0)

我认为您遇到以下问题,您不会在中间件上调用next,因此无法发送HTML文件。您还尝试拨打两次res.send(),而不应该打两次,express只能发送一个回复。我建议您更改以下api:

router.get('/', (req, res, next) => {
    console.log('api works');
    next();
});

现在api作品将在终端(nodejs)中登录,而不是在浏览器控制台中登录,并且HTML应该发送成功。

希望对您有所帮助!

答案 1 :(得分:0)

尝试app.use(express.static(path.join(__ dirname,'dist / mapit'))); 区别是使用“ dist / mapit”而不是仅使用“ dist”。

答案 2 :(得分:0)

您将server.js文件放在哪里?当我的server.js放在DIST文件夹中时,我遇到了同样的问题。

我将server.js文件上移了一层,因此它位于DIST文件夹的父目录中,并且我的站点文件css / js等均按预期加载。

相关问题