如何阻止NodeJS / Express缓存mongodb查询结果

时间:2018-02-16 15:47:32

标签: node.js mongodb express ionic2

似乎我的Node JS或Express正在缓存来自MongoDB的结果,这对某些人来说似乎是一个优势,但对我来说这是一个问题。我不希望缓存json响应。请建议如何阻止这一点。

如果您注意到我使用了res.headers和app.disable方法来阻止缓存,那么这是我的Server.js。

// set up ======================================================================
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var app = express();
var server = require('http').Server(app);
var mongoose = require('mongoose');                 // mongoose for mongodb
var port = process.env.PORT || 8000;                // set the port
var database = require('./config/database');            // load the database config
var morgan = require('morgan');
var methodOverride = require('method-override');
var io = require('socket.io')(server);
var cors = require('cors');
var messageId = {};

// configuration ===============================================================
// Connect to DB
mongoose.connect(database.remoteUrl)
mongoose.Promise = global.Promise;
mongoose.connection.on('error', function(e) {
    console.log('Can not connect Error:>>',e);
    process.exit();
});
mongoose.connection.once('open', function(d) { 
    console.log("Successfully connected to the database");
})
//app.use(express.static('./public'));      // set the static files location /public/img will be /img for users
app.use(morgan('dev')); // log every request to the console
app.use(bodyParser.urlencoded({'extended': 'true'})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({type: 'application/vnd.api+json'})); // parse application/vnd.api+json as json
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request
app.use(bodyParser.urlencoded({extended:true}))
app.use(bodyParser.json())
app.use(cors());
app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Methods', 'DELETE, PUT');
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Cache-Control", "no-cache, no-store, must-revalidate");
    res.header("Pragma", "no-cache");
    res.header("Expires", 0);
    next();
 });
app.disable('view cache');
io.set('origins', '*:*');
http = require('http'),
server = http.createServer(function (req, res) {
    //res.writeHead(200,{'content-type':'text/plain'});
    //  res.write("Sever On");
    // res.end();
}),
io = io.listen(server);
io.on('connection', function (socket) {
    console.log('User Connected -- Server Online');   
    socket.on('message', function (msg,msgId) {
        io.emit('message', "Hello");
        console.log("message from client:", msg);
         setInterval(function(){
          io.emit("messageStatus",msgId);
      },500)
   });
});

app.use(require('./app/routes.js'));
app.listen(port);
//server.listen(port);
console.log("App listening on port " + port);

这是我的Route.js

var express = require('express')
var app = module.exports = express.Router();
var UserProfile = require('./models/UserProfile');


app.get('/User', function (req, res) {
    UserProfile.find({
        EmailID: req.query.EmailID
    }, function (err, profile) {
        // if there is an error retrieving, send the error. nothing after res.send(err) will execute
        if (err) {
            return res.json({
                "success": false,
                "msg": err
            })
            console.log(err);
        }
        res.status(200).send(profile)
    });
});

这是我的provider.js

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ProfileProvider {
data : any
  constructor(public http: Http,) {

  }

  // public getProfile(EmailID){
  //   console.log(this.http.get(CONFIG.apiUrl+'User?EmailID='+EmailID).map(response => response.json().result));
  //   return this.http.get(CONFIG.apiUrl+'User?EmailID='+EmailID).map(response => response.json().result);

  // }

  public getProfile(EmailID){
 console.log("Provider,>>",EmailID)
    if (this.data) {
      return Promise.resolve(this.data);    }

    return new Promise(resolve => { 
      this.http.get('http://192.168.0.100:8000/User?EmailID='+EmailID)
        .map(res => res.json())
        .subscribe(data => {
          this.data = data;
          resolve(this.data);
        });
    });

  }

}

现在如果在我的浏览器上运行此(http://192.168.0.100:8000/User?EmailID=abc@abc.com)并且如果我更改了电子邮件ID,我会得到不同的回复。但是在离子应用程序中,即使在更改参数后,一些如何给出相同的响应

我正在使用AWS,我的MongoDB就在那里。

1 个答案:

答案 0 :(得分:2)

您的问题出在提供商处。您正在缓存数据属性中的api调用的结果。

  if (this.data) {
      return Promise.resolve(this.data);    }

尝试始终获取数据:

 public getProfile(EmailID){
    return new Promise(resolve => { 
      this.http.get('http://192.168.0.100:8000/User?EmailID='+EmailID)
        .map(res => res.json())
        .subscribe(data => {
          resolve(data);
        });
    });

  }