node.js - MEVN Stack 启动后重定向至主页

标签 node.js express vue.js redirect vuejs2

我目前正在创建网站的注册功能。 我正在使用 MEVN 堆栈,并且我已经设法让我的前端与我的数据库一起工作,但是一旦完成,我会得到一个

无法发布用户/注册

让我向您展示相关代码:

router.post('/signup', (req, res, next) => {
  //Verify if user email is associated with an account.
  User.find({email: req.body.email})
    .exec()
    .then(user => {
      //Returns message if user email is associated with an account.
      if(user.length >= 1) {
        getCode.fourHundred(res, 409, 
          'This email is already associated with an account.');
      } else { //If email is not found, makes a hashed password value. 
        if(req.body.password !== 'undefined') {
          bcrypt.hash(req.body.password, 10, (err, hash) => {
            if(err) {
              getCode.fiveHundred(res, err);
            } else {
              //If no errors occur, creates a new user. 
              const user = new User({
                _id: new mongoose.Types.ObjectId(),
                firstName: req.body.firstName,
                lastName: req.body.lastName,
                email: req.body.email,
                password: hash
              });
              // Saves user information to Database. 
              user.save()
              .then(result => {
                console.log(result);
                getCode.twoHundred(res, 201, 'User created')
                return res.redirect(301, 'localhost:8080')
              })
              .catch(getCode.fiveHundred(res, err))
            }
          });
        } 
      }
    });
});

我的前端如下:

<template>
  <main class="container">
    <h1> Sign Up</h1>
    <form class="grid-container" action="/users/signup" method="POST">
      <label class="label" for="first-name">First Name:</label>
      <input
        id="first-name"
        type="text"
        class="first-name input form-control"
        placeholder="First Name"
        v-model="firstName"
        required>

      <label class="label" for="last-name" >Last Name:</label>
      <input id="last-name"
         type="text"
         class="last-name input form-control"
         placeholder="Last Name"
         v-model="lastName"
         required>
      <label class="label" for="email" >Email:</label>
      <input id="email"
         type="email"
         class="email input form-control"
         placeholder="example@example.com"
         v-model="email"
         required>
      <label class="label" for="password">Password:</label>
      <input id="password"
         type="password"
         class="password input form-control"
         placeholder="Password"
         v-model="password"
         required>
      <div class="button-grid">
        <button
          class="button"
          type="submit"
          @click="signUp">
            Sign Up
        </button>
      </div>

    </form>
  </main>
</template>

<script>
import AuthenticationService from '@/services/AuthenticationService.js'

export default {
  name: 'SignUp',
  data () {
    return {
      firstName: '',
      lastName: '',
      email: '',
      password: ''
    }
  },
  methods: {
    async signUp () {
      const response = await AuthenticationService.signUp({
        firstName: this.firstName,
        lastName: this.lastName,
        email: this.email,
        password: this.password
      })
      console.log(response)
      setTimeout(() => this.redirect(), 1000)
    },
    redirect () {
      this.$router.push({ name: 'BuyAndSell' })
    }
  }
}
</script>

我正在使用 axios 将前端连接到后端。


export default () => axios.create({
  baseURL: 'http://localhost:3000/'
})
import api from '@/services/api'

export default {
  signUp (credentials, res) {
    return api().post('/users/signup', credentials)
  }
}

我尝试过通过 Vue 进行重定向,也尝试过通过 Express,但一无所获。

编辑:我还添加了此代码,因为这些是我重构以稍微清理代码的一些函数。

const getFiveHundredErrors = (res, err) => {
    console.log(err);
    return res.status(500).json({
      error: err
    });
  };

  const getfourHundredErrors = (res, code, message) => {
    return res.status(code).json({
      message: message
    })
  };

  const getTwoHundredSuccessCodes = (res, code, output, token) => {
    return res.status(code).json({
      output: output,
      token: token || null
    })

  }

  module.exports = { 
    fiveHundred: getFiveHundredErrors, 
    fourHundred: getfourHundredErrors, 
    twoHundred: getTwoHundredSuccessCodes }

这是app.js 文件。 我的控制台出现 500 错误,这可能是 .catch() 中的错误,也许错误就在那里?但我不确定如何让代码在创建用户后重定向回主页。此外,即使正在创建用户,也不会向我显示 200 状态。

const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');

const app = express();
const port = process.env.PORT || 3000;

const userRoutes = require('./api/routes/users');
const productRoutes = require('./api/routes/products');
const savedItemsRoutes = require('./api/routes/savedItems');

//I removed the mongodb.connect function to avoid exposing that info, even though I have the password stored in a .env file. 

//Middleware.
app.use(morgan('dev'))
app.use('/uploads', express.static('uploads'))
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(cors());

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 
  'Origin, X-Requested-Width, Content-Type, Accept, Authorization'
  );
  if(req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Methods', 
    'PUT', 'POST', 'PATCH', 'DELETE', 'GET');
    return res.status(200/json({}));
  }
  next();
});

// Request Handling Routes. 
app.use('/users', userRoutes);
app.use('/products', productRoutes);
app.use('/savedItems', savedItemsRoutes);

其他问题: 我有点明白这里发生了什么,但我不确定在哪里可以解决它。我知道一旦发送原始响应,我必须返回一些 res.status,但我只是对我的代码流程有点困惑,我试图跟踪错误消息将我带到哪里,但此时我只是无能为力。

(node:28036) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:535:11)
    at ServerResponse.header (/Users/edgarnegron/Projects/llevatelopr/server/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/Users/edgarnegron/Projects/llevatelopr/server/node_modules/express/lib/response.js:170:12)
    at ServerResponse.json (/Users/edgarnegron/Projects/llevatelopr/server/node_modules/express/lib/response.js:267:15)
    at getTwoHundredSuccessCodes (/Users/edgarnegron/Projects/llevatelopr/server/api/routes/users.js:112:20)
    at /Users/edgarnegron/Projects/llevatelopr/server/api/routes/users.js:40:17
    at processTicksAndRejections (internal/process/task_queues.js:97:5)

最佳答案

问题在于表单操作会将您带离 SPA 并进入错误的路线。实际上,您在表单提交上做了两件事:

1) 单击操作调用 signUp 方法。这正在创建用户,尽管我们看不到服务代码。

2)表单操作

这是一个糟糕的设计,原因有两个。您不应该像这样生成 2 个单独的调用,也不应该以这种方式使用表单操作,否则您将离开单页应用程序。还有前端和后端重定向。完全删除表单操作/方法。这就是让您远离 SPA(并进入显示错误消息的错误路线)的原因。一般来说,您不会将表单操作与 SPA 一起使用,因为它会让您离开应用程序。

问题 2

将保存后代码更改为:

user.save()
  .then(result => {
    return res.status(201).send(result);
  })

这将设置状态并发送回您刚刚创建的用户,只要 save 也返回它。不需要 301。

关于node.js - MEVN Stack 启动后重定向至主页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60360988/

相关文章:

sql-server - 从 Node js调用存储过程

javascript - 类型错误 : exphbs is not a function

javascript - 运行快车路线

mysql - jade 嵌套循环 mysql 数组

javascript - document.elementFromPoint(x, y) 未报告正确的子元素

javascript - Sequelize.js/Node.js/Express.js : Tasks. findAll()返回 TypeError:无法读取未定义的属性 'findAll'

javascript - 将express-babelify-middleware 与 FeathersJS 结合使用

node.js - 需要文件夹作为模块在另一个文件夹作为模块

javascript - 如何在 vue3 应用程序(vscode)中配置 Stylelint 以在保存时进行 lint

javascript - 将复选框链接到 Vue.js 中的列表项