我在后端有一个MongoDB,在前端有一个inMemoryDataService,但是每个导致另一个中断。例:
1.如果我正在运行inMemoryDataService,则我的后端注册/登录将无法进行。
2.如果我仅运行mongo,则不会加载我的api /情感。

任何建议要么两者都起作用,要么建议后端替换inMemoryDataService。谢谢

内存数据服务

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:[email protected]:2222/mongodbdb",
    "apiUrl": "http://localhost:4000",
    "secret": "Bearer"
}

最佳答案

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

app.module.ts

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

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

      ],

10-08 08:51