【发布时间】:2020-09-01 13:52:13
【问题描述】:
这里是登录组件。 当我尝试将发布消息发送回 nodejs 服务器时遇到问题。
另外,当我尝试使用邮递员发送帖子请求时,一切正常。所以后端部分似乎工作正常。
我试图在这里找到问题,但我无法将前端部分与后端(节点 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);
【问题讨论】:
-
有什么问题?
-
提交表单时页面是否刷新?为此,您需要在
handleSubmit上event.preventDefault() -
@PrateekThapa 问题是发布请求永远不会到达后端。此外,在 await 语句的上方,我有一个永远不会执行的 console.log 语句
-
您是否尝试过在本地主机的 URL 上使用
http而不是https? -
@PrateekThapa 服务器实际上是 https。但我现在试了一下,没有用。出现错误:TypeError: NetworkError when trying to fetch resource. 在 fetch 语句中。
标签: node.js reactjs https credentials