Uncaught SyntaxError:意外的令牌<-json格式

时间:2018-09-15 21:42:38

标签: javascript json express

我知道这个问题已经问过很多次了。 我仍然找不到错误的原因。 我了解这可能与json中的html输出有关,这是错误的

Uncaught SyntaxError: Unexpected token <

这是我的 api.js ,用于连接数据库并获取数据

const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const ObjectID = require('mongodb').ObjectID;

// Connect
const connection = (closure) => {
    return MongoClient.connect('mongodb://localhost:27017/mean', (err, db) => {
        if (err) return console.log(err);
        closure(db);
    });
};

// Error handling
const sendError = (err, res) => {
    response.status = 501;
    response.message = typeof err == 'object' ? err.message : err;
    //res.status(501).json(response);
    console.log('error')
};

// Response handling
let response = {
    status: 200,
    data: [],
    message: null
};

// Get users
router.get('/users', (req, res) => {
    connection((db) => {
        db.collection('users')
            .find()
            .toArray()
            .then((users) => {
                response.data = users;
                //res.json(response);
                //res.send(json(response))
                console.log('works')
            })
            .catch((err) => {
                //sendError(err, res);
                console.log('error')
            });
    });
});

server.js

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();

// API file for interacting with MongoDB
const api = require('./server/routes/api')

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

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// API location
app.use('/api', api);

// Send all other requests to the Angular app
//add extra segment in destination path 
app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, 'dist/mean-app/index.html'));
});

//Set Port
const port = process.env.PORT || '3000';
app.set('port', port);

const server = http.createServer(app);

server.listen(port, () => console.log(`Running on localhost:${port}`));

您可以看到我已注释掉尝试查找格式错误的JSON的响应数据行。 没有任何安慰 您能看到我想念的问题吗?

0 个答案:

没有答案