简体   繁体   中英

Fetch post api from React Client to express server causes error

I'm trying to send user id and password in React frontend (running on localhost:8080) to express backend server(running on localhost:5000) using post method, but when I click button for submit it says cannot Post /login

Below is my code

import React, { Component } from 'react';
//import'whatwg-fetch';

function postSend(url, data) {
  return fetch(url, {
    credentials: 'same-origin',
    mode: 'cors', 
    method: 'POST', // 'GET', 'PUT', 'DELETE', etc.
    body: JSON.stringify(data), // Coordinate the body type with 'Content-Type'
    headers: new Headers({
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }),
  }).then((res) => res.json())
  .then((result) => console.log(result))
  .catch((error) =>{
    console.error(error, 'postRequest error');
  })
};

class Signup extends Component {
  constructor(props){
    super(props);
    this.state = { id: "", password: ""}
  }
  componentDidMount() {
    const API = 'http://localhost:8080/';
    const DEFAULT_QUERY = 'routes';
    fetch(API + DEFAULT_QUERY, {
  headers : { 
    'Content-Type': 'application/json',
    'Accept': 'application/json'
   },
   mode: 'cors'

  }).then(response => response.json())
    .then(data => this.setState({ data }))
    .catch(function(err) {console.log(err)});
}

  handleChange = event => {
    this.setState({ [event.target.name] : event.target.value });
  };
  handleSubmit(event) {
    event.preventDefault();
    postSend('http://localhost:5000/login', this.state);


  }
    render() { 
        return ( <div>

            <h1>Welcome to Secret Admirer</h1>
            <form action = "/login" method = "POST"  > <hr/>
                <label>Enter Your Credentials to sign up</label>
                <div className ="form-group">
                <p>user id: 
                <input  type="text" value = {this.state.id} onChange={this.handleChange} name="id" placeholder="Enter your ID..."  required />
                </p><br/></div>
                <div className = "form-group">
                <p>Password: 
                <input type="text" value = {this.state.password} onChange={this.handleChange} name="password" placeholder="Enter your password" required />
                </p><br/></div>
             <button className = "btn btn-success" type="submit" value="Sign up" onSubmit={this.handleSubmit}> Sign Up</button>
            </form>

            </div>

        )}
}

export default Signup;
const express = require('express');
const bodyParser = require('body-parser');
const user = require('../db/user');

const router = express.Router();
var urlencodedParser = bodyParser.urlencoded({extended: false});


//Sign Up
router.post('/login', function(req,res){
    console.log(req.body);
    var newUser = new user.User(req.body);
    newUser.save().then(item => {
        res.redirect('/signin.html');
    }).catch(err => {
        res.status(400).send(err,"Unable to save to database");
    });
});


//Sign in logic
router.post('/signin', urlencodedParser, async(req,res) => {
    // check is id exist
    let userid = await user.User.findOne({id: req.body.id});
    if (!userid) {
        res.status(400).send('Invalid id please sign up');
    } else {
        let userpass = await user.User.findOne({
            id: req.body.id,
            password: req.body.password
        });
        if (!userpass) {
            return res.status(400).send('Wrong password');
        }
        res.redirect('/login-success.html');
    }
});

module.exports = router;

I would like POST call to work instead of getting cannot POST /login

In addition to the CORS requirement which you stated you've done,

Your form is pointing to localhost:8080/login which is in your React application, not express. change the onSubmit method to the form instead of the button.

render() { 
        return ( 
          <div>
            <h1>Welcome to Secret Admirer</h1>
            <form onSubmit={this.handleSubmit}> <hr/>
                <label>Enter Your Credentials to sign up</label>
                <div className ="form-group">
                <p>user id: 
                <input  type="text" value = {this.state.id} onChange={this.handleChange} name="id" placeholder="Enter your ID..."  required />
                </p><br/></div>
                <div className = "form-group">
                <p>Password: 
                <input type="text" value = {this.state.password} onChange={this.handleChange} name="password" placeholder="Enter your password" required />
                </p><br/></div>
             <button className = "btn btn-success" type="submit" value="Sign up"> Sign Up</button>
            </form>

            </div>

        )
}

your res.redirect() in the express application should also use a full path. If you're redirecting like this res.redirect('/signin.html'); , it would redirect to localhost:5000/signinhtml instead of your React application.

Update const API = 'http://localhost:8080/'; to const API = 'http://localhost:5000/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM