验证时req.user未定义

时间:2019-02-19 11:08:22

标签: javascript node.js express

验证用户身份后,

{ "query": { "match": { "title": "birds" } }, "rescore": { "query": { "query_weight": 1.0, "rescore_query": { "match": { "description": "colorful" } }, "rescore_query_weight": 1.0 }, "window_size": 500 }, "sort": [ { "_script": { "order": "asc", "script": { "params": { "Fantasy": 0, "Thriller": 1, "Detective": 2 }, "source": "params[doc['genre.keyword'].value]" }, "type": "number" } }, { "_score": "desc" } ] } 未定义。它可以更早地工作,但不确定我做了什么。

现在,它当前呈现

  

{}

路线/用户

req.user

app.js

router.get('/user', (req, res, next) => {
        res.status(200).send({auth: req.user}); // renders {}
});

passport.js

var express = require('express');
var app = express();
var userRoute = require('./routes/users');
var postRoute  = require('./routes/posts');
var bodyParser = require('body-parser');
var logger = require('morgan');
var models = require('./models');
var User = require('./models/user');
var session = require('express-session');
var cookieParser = require('cookie-parser') ;
var cookieSession = require('cookie-session');
var dotenv = require('dotenv');
var env = dotenv.config();
var cors = require('cors');
const port = process.env.PORT || 8000;
const passport = require('passport');
const path = require('path');
const allowOrigin = process.env.ALLOW_ORIGIN || '*'

// CORS Middleware

if (!process.env.PORT) {
  require('dotenv').config()
}

if (!process.env.PORT) {
  console.log('[api][port] 8000 set as default')
  console.log('[api][header] Access-Control-Allow-Origin: * set as default')
} else {
  console.log('[api][node] Loaded ENV vars from .env file')
  console.log(`[api][port] ${process.env.PORT}`)
  console.log(`[api][header] Access-Control-Allow-Origin: ${process.env.ALLOW_ORIGIN}`)
}


app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false })); 


// allowCrossDomain = function(req, res, next) {
// res.header('Access-Control-Allow-Origin', 'http://localhost:8000'); // your website
// res.header('Access-Control-Allow-Credentials', 'true');
// res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
// res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// if ('OPTIONS' === req.method) {
//     res.send(200);
// } else {
//     next();
// }};

app.use(cors({
  origin: process.env.ALLOW_ORIGIN,
  credentials:false,
  allowedHeaders: 'X-Requested-With, Content-Type, Authorization, origin, X-Custom-Header',
  methods: 'GET, POST, PATCH, PUT, POST, DELETE, OPTIONS',

}))

app.use(session({
  secret : 'nodeauthsecret',
  resave: false,
 saveUninitialized: true,

}));

app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport);
require('./config/passport-github')(passport);

app.use(function(req, res, next) {
  res.locals.user = req.user; // This is the important line
  console.log(res.locals.user);
  next();
});

// app.use(function(req, res, next) {
//   res.setHeader("Access-Control-Allow-Origin", "*");
//   res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// });



app.use('/api/users', userRoute )
app.use('/api/posts',  postRoute )

3 个答案:

答案 0 :(得分:1)

成功登录后

req.user = user;

答案 1 :(得分:0)

在您的passport.js文件中,您应该删除

const passport = require('passport'),

在您从app.js传递过来时

答案 2 :(得分:0)

似乎将其添加到我的路由和会话变量之上似乎使我可以访问req.user

Private Sub Form_Load()

    Dim subject As String, Body As String, EmailAddress As String
    Dim rs As Object, recount As Integer, count As Integer

    Set rs = Me.RecordsetClone

    If rs.RecordCount > 0 Then

        rs.MoveLast

        rs.MoveFirst

        recount = rs.RecordCount

        For count = 1 To recount

            EmailAddress = rs.[email]

            subject = "Action Required"

            Body = rs.VendorName & " " & "is due for oversight review process"

            DoCmd.SendObject , , , EmailAddress, , , subject, Body, False
            rs.MoveNext

        Next count

    End If

End Sub

app.js

// CORS Middleware
app.use(function (req, res, next) {

  // Website you wish to allow to connect
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');

  // Request methods you wish to allow
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

  // Request headers you wish to allow
  res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

  // Set to true if you need the website to include cookies in the requests sent
  // to the API (e.g. in case you use sessions)
  res.setHeader('Access-Control-Allow-Credentials', true);

  // Pass to next layer of middleware
  next();
});