404未找到 在React代码中的http://localhost:8081/forgot-password。

huangapple go评论107阅读模式
英文:

404 not found http://localhost:8081/forgot-password in react code

问题

I'm sorry, but it seems like you've provided a lengthy code snippet along with its description. To better assist you, please let me know which specific part you would like me to translate.

英文:

I'm trying to add a forgot password functionality to my login/register code and I'm getting a 404 not found error. I belive it is coming from my react because I commented out my node.js to see if I get a different error and I still get the same error.

404未找到 在React代码中的http://localhost:8081/forgot-password。

My ForgotPassword.component.js code:

/* 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',
padding: '1em',
margin: '1em',
};

export const homeButton = {
  background: 'mediumpurple',
   padding: '1em',
   margin: '1em',
     };

     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,0,36,1) 0%, rgba(9,9,121,1) 25%, rgba(8,177,5,1) 62%, 
    rgba(0,212,255,1) 100%)',
     color: 'white',
  };

 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,
     messageFromServer: '',
     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',
        showNullError: false,
        });
       }
     } catch (error) {
       console.error(error.response.data);
      if (error.response.data === 'email not in db') {
        this.setState({
        showError: true,
        messageFromServer: '',
        showNullError: false,
        });
        }
        }
        }
        };

      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'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;

Where I declare my routes in 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>

Any ideas? I'm stressing

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

I also get this on my nodejs command line

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)

答案1

得分: 1

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

英文:

Is your node application running on port 8081 as well through proxy? If not, axios is making a request to your frontend application, not your node server.

答案2

得分: 0

Add this to your client package.json

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

Make API call like below

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

Add this to your client package.json

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

MAke API call like below

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

huangapple
  • 本文由 发表于 2020年9月11日 04:21:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/63837181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定