Prooblem connecting the front with the back

2019-08-27 03:10发布

问题:

I have a problem, I don't know what I touched but it seems that my front does not connect to the back. -With the postman, the back gives me the token, so I don't think it's a problem with the back. -But when I try to log in I get "Cannot POST / Admin", admin is simply the route not by admin permissions. -In the console of the page I see "Failed to load resource: the server responded with a status of 404 (Not Found)" So it seems that there is no connection between the two. -While in the back console it puts the same thing all the time, a console that I put and that there are no errors "OPTIONS / api / auth 204 0.089 ms - 0 POST / api / auth - - ms - - Connected successfully to server " -Another error that has come out to me sometimes, although I think it is a warning is this "(node: 10388) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option {useNewUrlParser: true} to MongoClient.connect. " In short, I don't know what I've touched and I've been looking at it for two days and I don't know where to go.

Right now I am using React, Nodejs, Redux and MongoDB

Login.tsx

import React, { useState } from "react";
import "../styles/Admin.css";
import { connect } from "react-redux";
import * as actions from "../actions/actions";


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 => {
        console.log(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);

and here Api.js

const express = require('express');
const jwt = require('jsonwebtoken');
const mongo = require('mongodb');
const assert = require('assert');


const router = express.Router();
const md5 = require('md5');
// Connection URL
const mongoUrl = 'mongodb://localhost:27017';
// Database Name
const mongoDBName = 'ardalesturweb';


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

const secret = 'mysecret';


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);
    console.log(req.body.username)

    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();
  });
});

Cannot POST /

when the postman works with api. I don't know if I have put something wrong in the front, because the back seems to be correct

回答1:

I don't have enough points to comment, so here are a few things you should clarify in the question and might help you in fixing the problem.

  1. 404("Not Found") is the error that you report, it means the server does not have a handler for the relevant endpoint so make sure the /Admin endpoint is correct. It is not present in the Api.js file. Make sure the middleware prefix is correct; is it /api/admin or just /admin .

  2. the /api/auth endpoint seems to be working correctly; which is why the console is working. You have probably not posted the code for the frontend where the call to /admin is being made.

Comment/Edit with these suggestions and maybe we can solve this.