【问题标题】:Cannot POST /Admin无法发布/管理员
【发布时间】:2019-08-20 15:12:46
【问题描述】:

我在节点 js 中使用我的 api 连接反应,但是当连接到登录时,唯一出现的是“无法 POST / Admin” 我用过Postman,后面的部分好像是因为token返回了,但是我觉得两者的连接有些问题。

我正在研究 react、nodejs、redux 和 mongodb

interface IProps {}

interface IPropsGlobal {
  setToken: (t: string) => void;
  setName: (u: string) => void;
}

const Login: React.FC<IProps & IPropsGlobal> = props => {
  const [username, setUsername] = React.useState("");
  const [password, setPassword] = React.useState("");
  const [error, setError] = React.useState("");

  const updateUsername = (event: React.ChangeEvent<HTMLInputElement>) => {
    setUsername(event.target.value);
    setError("");
  };
  const updatePassword = (event: React.ChangeEvent<HTMLInputElement>) => {
    setPassword(event.target.value);
    setError("");
  };

  const signIn = () => {
    fetch("http://localhost:3006/api/auth", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        username: username,
        password: password
      })
    })
      .then(response => {
        if (response.ok) {
          response
            .text() 
            .then(token => {
              console.log(token);
              props.setToken(token);
              props.setName(username);

            });
        } else {
          setError("Usuario o Contraseña incorrectos");
        }
      })
      .catch(err => {
        setError("Usuario o Contraseña incorrectos.");
      });
  };


    return (

<div>

      <div className="section"></div>

      <h5 className="indigo-text">Please, login into your account</h5>
      <div className="section"></div>

      <div className="container">
        <div className="z-depth-1 grey lighten-4 row er" >

          <form className="col s12" method="post">
            <div className='row'>
              <div className='col s12'>
              </div>
            </div>

            <div className='row'>
              <div className='input-field col s12'>
                <input className='validate' name='email' id='email' value={username}
                      onChange={updateUsername}/>
                <label >Enter your email</label>
              </div>
            </div>

            <div className='row'>
              <div className='input-field col s12'>
                <input className='validate' type='password' name='password' id='password' value={password}
                      onChange={updatePassword} />
                <label >Enter your password</label>
              </div>
              <label >
                                <a className='pink-text' href='#!'><b>Forgot Password?</b></a>
                            </label>
            </div>

            <br />

              <div className='row'>
                <button type='submit' name='btn_login' className='col s12 btn btn-large waves-effect indigo'
                 onClick={signIn}>Login</button>
              </div>

          </form>
        </div>
      </div>
      <a href="#!">Create account</a>
      </div>
    );
};

const mapDispatchToProps = {
  setToken: actions.setToken,
  setName: actions.setName
};

export default connect(
  null,
  mapDispatchToProps
)(Login);



邮递员返回令牌

api 控制台显示:

POST /api/auth - - ms - -
Connected successfully to server

在网页中 Failed to load resource: the server responded with a status of 404 (Not Found)

我之前在其他项目中使用过此代码或类似的代码,但我不明白这次发生在我身上的是什么

【问题讨论】:

  • 我猜您的问题出在 API 端点代码中。你能把这段代码也给我们看看吗?
  • 我不知道如何编辑,所以在回复中发布,对不起

标签: node.js reactjs mongodb redux


【解决方案1】:
const md5 = require('md5');
// Connection URL
const mongoUrl = 'mongodb://localhost:27017';
// Database Name
const mongoDBName = 'ArdalesTur';


/* GET users listing. */
router.get('/', (req, res) => {
  res.send('respond with a resource');
});

const secret = 'mysecret';

// para interactuar con la base de datos
router.post('/auth', (req, res) => {
  mongo.MongoClient.connect(mongoUrl, (err, client) => {

    assert.equal(null, err);
    console.log('Connected successfully to server');

    const db = client.db(mongoDBName);

    const query = db.collection('Admin').find({
      username: req.body.username,
      password: md5(req.body.password),
    });

    query.toArray().then((documents) => {
      if (documents.length > 0) {
        const token = jwt.sign(
          {
            _id: documents[0]._id,
            username: documents[0].username
          },
          secret,
          // {
          //     expiresIn: 86400
          // }
        );
        res.send(token);
      } else {
        res.status(400).send('Invalid credentials');
      }
    });

    client.close();
  });
});

这里有 api

【讨论】:

  • 我没有看到您使用 /api/ 作为基本路径。也许您可以尝试在您的客户端代码中调用“localhost:3006/auth”。控制台中的 404 错误意味着找不到给定路由(/api/auth)的端点
  • 我只是试图改变它,唯一的改变是在后台控制台中:“OPTIONS /auth 204 0.460 ms - 0 POST /auth 404 45.956 ms - 0”
猜你喜欢
  • 2023-03-25
  • 1970-01-01
  • 2019-07-21
  • 2013-08-15
  • 2019-02-09
  • 2016-11-21
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
相关资源
最近更新 更多