微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在响应代码中找不到404 http:// localhost:8081 / forgot-password

如何解决在响应代码中找不到404 http:// localhost:8081 / forgot-password

我正在尝试在我的登录/注册代码添加一个忘记密码的功能,但出现404 not found错误。我相信这是我的反应造成的,因为我注释掉了node.js来查看是否遇到其他错误,并且仍然遇到相同的错误

enter image description here

我的ForgotPassword.component.js代码

/* eslint-disable no-console */
import React,{ Component,Fragment } from 'react';
import PropTypes from 'prop-types';
import { TextField } from '@material-ui/core';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
import { Link } from 'react-router-dom';

import axios from 'axios';
const forgotButton = {
 background: 'purple',padding: '1em',margin: '1em',};
 const inputStyle = {
 margin: '.5em',};
  export const linkStyle = {
 textdecoration: 'none',color: 'white',};


  const SubmitButtons = ({ buttonText,buttonStyle }) => (
  <Fragment>
   <Button
     style={buttonStyle}
     type="submit"
     variant="contained"
     color="primary"
   >
    {buttonText}
  </Button>
</Fragment>
);
SubmitButtons.propTypes = {
 buttonText: PropTypes.string.isrequired,// eslint-disable-next-line react/forbid-prop-types
buttonStyle: PropTypes.object.isrequired,};
 export const registerButton = {
background: 'green',};

export const homeButton = {
  background: 'mediumpurple',};

     const LinkButtons = ({ buttonText,buttonStyle,link }) => (
    <Fragment>
    <Link style={linkStyle} to={link}>
    <Button variant="contained" color="primary" style={buttonStyle}>
     {buttonText}
    </Button>
    </Link>
   </Fragment>
   );
   const title = {
   pageTitle: 'Forgot Password Screen',};
   const headerStyle = {
    background:
       'linear-gradient(90deg,rgba(2,36,1) 0%,rgba(9,9,121,1) 25%,rgba(8,177,5,1) 62%,rgba(0,212,255,1) 100%)',};

 const HeaderBar = ({ title }) => (
  <div className="header">
    <AppBar position="static" color="default" style={headerStyle}>
     <Toolbar>
      <Typography variant="title" color="inherit">
      {title.pageTitle || 'Page Title Placeholder'}
      </Typography>
     </Toolbar>
   </AppBar>
  </div>
   );

 class ForgotPassword extends Component {
 constructor() {
  super();

 this.state = {
   email: '',showError: false,messageFromServer: '',showNullError: false,};
   }

 handleChange = name => (event) => {
 this.setState({
  [name]: event.target.value,});
 };

   sendEmail = async (e) => {
   e.preventDefault();
   const { email } = this.state;
   if (email === '') {
     this.setState({
     showError: false,showNullError: true,});
     } else {
    try {
      const response = await axios.post(
      'http://localhost:8081/forgot-password',{
         email,},);
      console.log(response.data);
      if (response.data === 'recovery email sent') {
        this.setState({
        showError: false,messageFromServer: 'recovery email sent',});
       }
     } catch (error) {
       console.error(error.response.data);
      if (error.response.data === 'email not in db') {
        this.setState({
        showError: true,});
        }
        }
        }
        };

      render() {
     const {
       email,messageFromServer,showNullError,showError  
       } = this.state;

    return (
   <div>
    <HeaderBar title={title} />
    <form className="profile-form" onSubmit={this.sendEmail}>
      <TextField
        style={inputStyle}
        id="email"
        label="email"
        value={email}
        onChange={this.handleChange('email')}
        placeholder="Email Address"
      />
      <SubmitButtons
        buttonStyle={forgotButton}
        buttonText="Send Password Reset Email"
      />
    </form>
    {showNullError && (
      <div>
        <p>The email address cannot be null.</p>
      </div>
    )}
    {showError && (
      <div>
        <p>
          That email address isn&apos;t recognized. Please try again or
          register for a new account.
        </p>
        <LinkButtons
          buttonText="Register"
          buttonStyle={registerButton}
          link="/register"
        />
      </div>
    )}
    {messageFromServer === 'recovery email sent' && (
      <div>
        <h3>Password Reset Email Successfully Sent!</h3>
      </div>
    )}
    <LinkButtons buttonText="Go Home" buttonStyle={homeButton} link="/" />
  </div>
   );
   }
   }

   export default ForgotPassword;

我在app.js中声明路线的地方

    <div className="container mt-3">
        <Switch>
          <Route exact path={["/","/home"]} component={Home}  />
          <Route exact path="/login" component={Login} />
          <Route exact path="/register" component={Register} />
          <Route exact path="/forgot-password" component={ForgotPassword} />
          <Route exact path="/profile" component={Profile} />
          <Route path="/user" component={BoardUser} />
          <Route path="/mod" component={BoardModerator} />
          <Route path="/admin" component={BoardAdmin} />
        </Switch>
        </div>
        </div>

有什么想法吗?我在强调

forgotPassword.js

const controller = require("../controllers/auth.controller");
const crypto = require("crypto");
const Sequelize = require("sequelize");
const nodemailer = require('nodemailer');

module.exports = (app) => {
app.post('/forgot-password',(req,res) => {
if (req.body.email === '') {
  res.status(400).send('email required');
 }
 console.error(req.body.email);
  User.findOne({
  where: {
    email: req.body.email,}).then((user) => {
  if (user === null) {
    console.error('email not in database');
    res.status(403).send('email not in db');
   } else {
    const token = crypto.randomBytes(20).toString('hex');
    user.update({
      resetPasswordToken: token,resetPasswordExpires: Date.Now() + 3600000,});

     const transporter = nodemailer.createTransport({
      service: 'gmail',auth: {
        user: `${process.env.EMAIL_ADDRESS}`,pass: `${process.env.EMAIL_PASSWORD}`,});

      const mailOptions = {
      from: 'MysqLDemoEmail@gmail.com',to: `${user.email}`,subject: 'Link To Reset Password',text:
        'You are receiving this because you (or someone else) have requested 
       the reset of the password for your account.\n\n'
        + 'Please click on the following link,or paste this into your 
        browser to complete the process within one hour of receiving it:\n\n'
        + `http://localhost:8081/reset/${token}\n\n`
        + 'If you did not request this,please ignore this email and your  
      password will remain unchanged.\n',};

      console.log('sending mail');

      transporter.sendMail(mailOptions,(err,response) => {
      if (err) {
        console.error('there was an error: ',err);
      } else {
        console.log('here is the res: ',response);
        res.status(200).json('recovery email sent');
      }
      });
       }
      });
       });
        };

POST http://localhost:8081/forgot-password 500 (Internal Server Error)
dispatchXhrRequest @ xhr.js:184
xhrAdapter @ xhr.js:13
dispatchRequest @ dispatchRequest.js:52
Promise.then (async)
request @ Axios.js:61
Axios.<computed> @ Axios.js:86
wrap @ bind.js:9
ForgotPassword.sendEmail @ ForgotPassword.component.js:114
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:306
executedispatch @ react-dom.development.js:389
executedispatchesInorder @ react-dom.development.js:414
executedispatchesAndRelease @ react-dom.development.js:3278
executedispatchesAndReleasetopLevel @ react-dom.development.js:3287
forEachAccumulated @ react-dom.development.js:3259
runEventsInBatch @ react-dom.development.js:3304
runExtractedpluginEventsInBatch @ react-dom.development.js:3514
handletopLevel @ react-dom.development.js:3558
batchedEventUpdates$1 @ react-dom.development.js:21871
batchedEventUpdates @ react-dom.development.js:795
dispatchEventForLegacyPluginEventSystem @ react-dom.development.js:3568
attemptTodispatchEvent @ react-dom.development.js:4267
dispatchEvent @ react-dom.development.js:4189
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
discreteUpdates$1 @ react-dom.development.js:21887
discreteUpdates @ react-dom.development.js:806
dispatchdiscreteEvent @ react-dom.development.js:4168

我也在我的nodejs命令行上得到了

dylanrychlik@gmail.com
ReferenceError: User is not defined
at C:\Users\dylan\Documents\node-js-jwt- 
auth\app\routes\forgotPassword.js:46:7
at Layer.handle [as handle_request] (C:\Users\dylan\Documents\node-js-jwt- 
auth\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\dylan\Documents\node-js-jwt- 
auth\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\dylan\Documents\node-js-jwt- 
auth\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\dylan\Documents\node-js-jwt- 
auth\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\dylan\Documents\node-js-jwt- 
auth\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\dylan\Documents\node-js-jwt- 
auth\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\dylan\Documents\node-js-jwt- 
auth\node_modules\express\lib\router\index.js:275:10)
at C:\Users\dylan\Documents\node-js-jwt-auth\app\routes\user.routes.js:10:5
at Layer.handle [as handle_request] (C:\Users\dylan\Documents\node-js-jwt- 
auth\node_modules\express\lib\router\layer.js:95:5)

解决方法

您的节点应用程序是否也通过代理在端口8081上运行?如果不是,则axios向您的前端应用程序而不是节点服务器发出请求。

,

将此添加到您的客户端package.json

  "proxy": "http://127.0.0.1:8080",

进行如下所示的API调用

const response = await axios.post(
      '/forgot-password',{
         email,},);

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。