InMemoryDataService导致MongoDB错误

时间:2018-04-10 15:15:33

标签: javascript mongodb typescript in-memory-database

我在后端有一个MongoDB,在前端有一个inMemoryDataService,但每个都会导致另一个中断。例: 1.如果我运行了inMemoryDataService,我的后​​端注册/登录将不起作用。 如果我只运行mongo,我的api /情绪就不会加载。

任何建议要么既有效,要么如何让后端替换inMemoryDataService。感谢

内存-data.service.ts

import { InMemoryDbService } from 'angular-in-memory-web-api';

export class InMemoryDataService implements InMemoryDbService {

  createDb() {


    const emotions = [
      { id: 11, name: 'HAPPY' },
      { id: 12, name: 'SAD' },
      { id: 13, name: 'STRESSED' },
      { id: 14, name: 'EXCITED' },
      { id: 15, name: 'EMBARRASSED' },
      { id: 16, name: 'SLEEPY' },
      { id: 17, name: 'SURPRISED' },
      { id: 17, name: 'ANXIOUS' },

    ];

    return {emotions};

}
}

server.js

require('rootpath')();
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
var expressJwt = require('express-jwt');
var path = require('path');
var config = require('config.json');

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

// use JWT auth to secure the api, the token can be passed in the authorization header or querystring
app.use(expressJwt({
    secret: config.secret,
    getToken: function (req) {
        if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') {
            return req.headers.authorization.split(' ')[1];
        } else if (req.query && req.query.token) {
            return req.query.token;
        }
        return null;
    }
}).unless({ path: ['/users/authenticate', '/users/register'] }));

// routes
app.use('/users', require('./controllers/users.controller'));
app.use('/emotions', require('/controllers/emotion.controller'));

// error handler
app.use(function (err, req, res, next) {
    if (err.name === 'UnauthorizedError') {
        res.status(401).send('Invalid Token');
    } else {
        throw err;
    }
});

// start server
var port = process.env.NODE_ENV === 'production' ? 80 : 4000;
var server = app.listen(port, function () {
    console.log('Server listening on port ' + port);
});

config.json

{
    "connectionString": "mongodb://mongodbuser:passsword@danu7.it.nuigalway.ie:2222/mongodbdb",
    "apiUrl": "http://localhost:4000",
    "secret": "Bearer"
}

1 个答案:

答案 0 :(得分:1)

找到答案:将passThruUnknownUrl: true添加到 app.module.ts 中的内存数据服务导入中,以便后端数据服务的http可以正确传递!

<强> app.module.ts

  imports: [
        BrowserModule,
        AppRoutingModule,
        HttpClientModule,
        HttpModule,
        FormsModule,

     //   BootstrapModalModule,
     HttpClientInMemoryWebApiModule.forRoot( InMemoryDataService, { passThruUnknownUrl: true } )

      ],