在响应代码中找不到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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-