![](/img/trans.png)
[英]Post request from fetch gives a 404 server error (javascript/express)
[英]Fetch post api from React Client to express server causes error
我正在嘗試使用post方法在React前端(在localhost:8080上運行)發送用戶ID和密碼來表示后端服務器(在localhost:5000上運行),但是當我單擊按鈕提交時它說不能發布/登錄
以下是我的代碼
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;
我想POST調用工作而不是獲取不能POST /登錄
除了你說過的CORS要求之外,
您的表單指向您的React應用程序中的localhost:8080/login
,而不是express。 將onSubmit方法更改為窗體而不是按鈕。
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>
)
}
Express應用程序中的res.redirect()
也應使用完整路徑。 如果您像這樣重定向res.redirect('/signin.html');
,它會重定向到localhost:5000/signinhtml
而不是你的React應用程序。
更新const API = 'http://localhost:8080/';
到const API = 'http://localhost:5000/'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.