提交凭据,连接与 nodejs 反应

Sumbit credentials, connect react with nodejs

这是登录组件。 当我尝试将 post 消息发送回 nodejs 服务器时遇到问题。

此外,当我尝试用 postman 发送 post 请求时,一切正常 ok.So 后端部分似乎正常工作。

我想在这里找到问题,但我无法将前端部分与后端(node js)连接起来

import React, { Component,useState } from 'react';
import '../css/Login.css'
import axios from 'axios';
import {withRouter} from 'react-router';
import url from '../services/url';
class Login extends Component{
    constructor(props){
        super(props)
        this.state = {
            username: "",
            password: "",
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(event) {    
        const target  = event.target;
        const targetName = target.name;
        if( targetName === "username"){
            this.setState({
                username: target.value
            })
        }
        else{
            this.setState({
                password: target.value
            })
        }
    }
    handleSubmit = async event => {
        try {
            await fetch(`https://localhost:8000/users/login`, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    username: this.state.username,
                    password: this.state.password
                })
            })
                .then(response => console.log(response))
                .catch(err => console.log(err));
        } catch (error) {
            console.log(error);
        }
  };
    render(){
        return (
            <div>
                <form  class="form-signin" onSubmit={this.handleSubmit}>
                    <div class="text-center mb-4">
                        <img class="mb-4" src="/docs/4.5/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72"/>
                        <h1 class="h3 mb-3 font-weight-normal">Floating labels</h1>
                    </div>

                    <div class="form-label-group">
                        <label for="inputUsername">Username</label>
                        <input type="text" name="username" id="inputUsername" value={this.state.username} onChange={this.handleChange} class="form-control" placeholder="Username" required="" autofocus=""/>
                    
                    </div>
                    <div class="form-label-group">
                        <label for="inputPassword">Password</label>
                        <input type="password"  name="password"  id="inputPassword" value={this.state.password} onChange={this.handleChange} class="form-control" placeholder="Password" required=""/>
                    </div>
                        <button class="btn btn-lg btn-primary btn-block" type="submit" >Sign in</button>
                    <p class="mt-5 mb-3 text-muted text-center">©2020</p>
                </form>
            </div>
        )
    }    
}
export default withRouter(Login);

您将 thenawait 一起使用,这是错误的。 await 本身解决了承诺,而旧的 .then returns 一个 thenable 你可以在 .then 上使用。

阅读 docs here 如何使用 async/await。

import React, { Component,useState } from 'react';
import '../css/Login.css'
import axios from 'axios';
import {withRouter} from 'react-router';
import url from '../services/url';

class Login extends Component{
    constructor(props){
        super(props)
        this.state = {
            username: "",
            password: "",
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleChange(event) {
        this.setState({ [e.target.name]: e.target.value })
    }

    handleSubmit = async event => {
      event.preventDefault();
  
        try {
            const response = await fetch(`http://localhost:8000/users/login`, {
                method: 'post',
                headers: {
                    'Content-Type': 'application/json',
                     'Accept': 'application/json',
                },
                body: JSON.stringify({
                    username: this.state.username,
                    password: this.state.password
                })
            })
            const jsoned = await response.json();
        } catch (error) {
            console.log(error);
        }
  };

    render(){
        return (
            <div>
                <form  class="form-signin" onSubmit={this.handleSubmit}>
                    <div class="text-center mb-4">
                        <img class="mb-4" src="/docs/4.5/assets/brand/bootstrap-solid.svg" alt="" width="72" height="72"/>
                        <h1 class="h3 mb-3 font-weight-normal">Floating labels</h1>
                    </div>

                    <div class="form-label-group">
                        <label for="inputUsername">Username</label>
                        <input type="text" name="username" id="inputUsername" value={this.state.username} onChange={this.handleChange} class="form-control" placeholder="Username" required="" autofocus=""/>
                    
                    </div>
                    <div class="form-label-group">
                        <label for="inputPassword">Password</label>
                        <input type="password"  name="password"  id="inputPassword" value={this.state.password} onChange={this.handleChange} class="form-control" placeholder="Password" required=""/>
                    </div>
                        <button class="btn btn-lg btn-primary btn-block" type="submit" >Sign in</button>
                    <p class="mt-5 mb-3 text-muted text-center">©2020</p>
                </form>
            </div>
        )
    }    
}

export default withRouter(Login);

我只是在服务器端添加了这段代码.. 浏览器似乎阻止了请求..

    res.header("Access-Control-Allow-Origin", "https://localhost:8000");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Access-Control-Allow-Headers, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization");
    res.header('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, PATCH, OPTIONS');