【问题标题】:MEVN Stack Redirecting to Home page after singing up唱歌后 MEVN 堆栈重定向到主页
【发布时间】:2020-06-07 04:50:47
【问题描述】:

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

cannot POST users/signup

让我告诉你相关的代码:

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)

【问题讨论】:

  • 此代码与错误无关。你能显示你在 Express 中处理users/signup 路线的位置吗? app.post('users/signup', ... 形式的东西这个消息基本上意味着不存在这样的路由处理程序。
  • @dan 是的,我明白你的意思。但是,每当我在我的数据库上创建一个用户以及当我去 mongoose 时,我都能够看到控制台日志。我不知道之后如何重定向到我的主页。
  • @dan 我已经发布了整个内容,但没有显示格式错误,我现在修复了它。感谢您花时间回答我的问题。
  • 您是说您创建了一个用户,尽管 Express 说它找不到路线,或者您以其他方式创建用户?您还应该显示任何/users 路线。
  • @dan ^^ 显然在您的帮助下修复了它。在您写此消息之前,我认为这是我必须按照您的建议做的事情。非常感谢,我已经尝试解决这个问题将近一个星期了。你是一个活生生的救星。

标签: node.js express vue.js redirect vuejs2


【解决方案1】:

问题在于表单操作会将您从 SPA 中带走并转到错误的路线。你实际上在表单提交上做了两件事:

1) 点击动作调用signUp 方法。这是在创建用户,虽然我们看不到服务代码。

2) 表单动作

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

问题 2

将您的保存后代码更改为:

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

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

【讨论】:

    猜你喜欢
    • 2020-07-01
    • 2022-01-14
    • 1970-01-01
    • 2022-08-22
    • 2021-01-26
    • 2021-01-16
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多