VueJs - 承诺返回但重定向不会发生

时间:2018-06-07 18:59:13

标签: javascript node.js redirect vue.js

我正在使用Vue,Node,Express和Mongodb构建登录。我可以在注册时成功将用户保存到数据库,但我希望在注册后将用户重定向到其他组件。

问题:我的用户保存后没有任何反应,我留在同一个注册组件上。我不确定我是否想从服务器或客户端重定向我的响应..

我看到控制台日志registering,但我看不到控制台日志registration successful,我不知道为什么......有人可以帮忙吗?

-------客户代码-------

Registration.vue

<template>
  <v-layout >
    <v-flex xs6 offset-xs3>
      <div class="white elevation-2">
        <v-toolbar flat dense class="blue" dark>
          <v-toolbar-title>Register</v-toolbar-title>
        </v-toolbar>

        <div class="pl-4 pr-4 pt-2 pb-2">
          <v-text-field label="email" v-model="email"/>
          <br>
          <v-text-field label="password" v-model="password"/>
          <br>
          <div class="error" v-html="error"></div>
          <v-btn class="blue" dark @click="register">Register</v-btn>
        </div>
      </div>
    </v-flex>
  </v-layout>
</template>

<script>
  import AuthenticationService from '../services/AuthenticationService'
  export default {
    data () {
      return {
        email: '',
        password: '',
        error: null
      }
    },
    methods: {
      async register (res, req) {
        try {
          console.log('registering');
          const response = await AuthenticationService.register({
            email: this.email,
            password: this.password
          });
          res.status(200).send('registration successful'); // I NEVER SEE THIS!!
          console.log('registration successful: ' + response.data);
          this.$router.push('dashboard')
        } catch (error) {
          console.log('error during reg on front eng');
          this.error = error.response.data.error;
        }
      }
    }
  }
</script>

authenticationService.js

import Api from '../services/Api'

export default {
  register(credentials) {
    return Api().post('register', credentials);
  },
  login(credentials) {
    return Api().post('login', credentials);
  }
}

Api.js

import axios from 'axios';

export default() => {
  return axios.create({
    baseURL: 'http://localhost:5000'
  })
}

-------服务器代码-------

index.js

const express = require("express");
const mongoose = require('mongoose');
const cookieSession = require('cookie-session');
const passport = require('passport');
const bodyParser = require('body-parser');
const keys = require('./config/keys');
const cors = require('cors');

require('./models/User');
require('./services/passport');


// grab db access for admin rights
mongoose.connect(keys.mongoURI);

//create an app using express route handlers
const app = express();
app.use(cors());

app.use(bodyParser.json());
// allow the app to use cookies
app.use(
    cookieSession({
        maxAge: 30 * 24 * 60 * 60 * 1000,
        keys: [keys.cookieKey]
    })
);

// tell passport to use cookies
app.use(passport.initialize());
app.use(passport.session());

// this file returns a function which uses app object as an arg
require('./routes/authRoutes')(app);

const PORT = process.env.PORT || 5000;
app.listen(PORT);

authRoutes.js

const passport = require('passport');
const authenticationController = require('../controllers/AuthenticationController');
const authenticationControllerPolicy = require('../policies/AuthenticationControllerPolicy');

/**
 * Authentication routing for Google OAuth
 * @type {Passport}
 */
module.exports = (app) => {

    app.post('/register',
        //authenticationControllerPolicy.register,
        authenticationController.register);


};

authenticationController.js

const jwt = require('jsonwebtoken');
const config = require('../config/config');
//const bcrypt = require('bcrypt');

const mongoose = require('mongoose');

const User = mongoose.model('users');

module.exports = {

    async register(req, res) {
        console.log('authenticationController: ' + JSON.stringify(req.body));

        try {
            const user = await User.find({email: req.body.email}).count();

            if(user) {
                console.log('user exists in db');
                return;
            } else {
                console.log('creating new user entry');
                const newUser = await new User({
                    email: req.body.email,
                    password: req.body.password
                }).save();
                res.send(newUser);
            }

        } catch (error) {
            console.log(error);
        }
    }
};

2 个答案:

答案 0 :(得分:0)

您确定AuthenticationService.register确实正确地回复了承诺吗?

  

await表达式导致async函数执行暂停,直到满足Promise,已解决或拒绝,并在执行后继续执行async函数。恢复后,await表达式的值是已完成Promise的值。

有关详细信息,请参阅MDN web docs - await

答案 1 :(得分:0)

一旦我在Registration.vue注释掉这一行,一切正常。

res.status(200).send('registration successful');

不确定原因..