我有一个在后端运行的 Node/Express 服务器和一个 React 前端,我正在尝试制作最简单的 API - 但无论我做什么,我似乎都会在 post 请求中收到错误 404。我试过将代理添加到 package.json 中,删除代理并在地址中包含端口,即 http://localhost:5000/createaccount ,包括 http://localhost:5000 的代理并在发布请求中使用“/createaccount”。我用 CORS 和 header 尝试了各种方法,但似乎没有任何效果。
当我转到 http://localhost:5000/createaccount 时在我的浏览器中,它确实成功地记录了“hello world”,所以我知道服务器正在运行。我也知道现在实际上没有对发送的数据做任何事情,只是暂时尝试建立连接!我也尝试取消注释/注释掉获取请求中的大部分内容,但都无济于事。
Server.js代码:
// server.js
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const PORT = 5000;
const cors = require("cors");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.get("/createaccount", (req, res) => {
console.log("test");
res.append("Access-Control-Allow-Origin", ["*"]);
res.append("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
res.append("Access-Control-Allow-Headers", "Content-Type");
res.send("testComplete");
});
app.listen(PORT, function() {
console.log("Server is running on Port: ", PORT);
});
CreateAccountjs 代码:
// Create.js
import React, { Component } from "react";
import axios from "axios";
import { Button, FormGroup, FormControl, FormLabel } from "react-bootstrap";
export default class CreateAccount extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.state = {
email: "",
password: ""
};
}
handleChange = e => {
this.setState({
[e.target.id]: e.target.value
});
};
handleSubmit = e => {
e.preventDefault();
const data = {
email: this.state.email,
password: this.state.password
};
fetch("http://localhost:5000/createaccount", {
method: "POST", // *GET, POST, PUT, DELETE, etc.
mode: "cors", // no-cors, cors, *same-origin
headers: {
"Content-Type": "application/json"
// "Access-Control-Allow-Origin": "*"
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: "follow", // manual, *follow, error
referrer: "no-referrer", // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
}).then(res => console.log(res));
};
render() {
return (
<div className="CreateAccount">
<form onSubmit={this.handleSubmit.bind(this)}>
<FormGroup controlId="email">
<FormLabel>Email</FormLabel>
<FormControl
type="email"
value={this.state.email}
onChange={this.handleChange.bind(this)}
/>
</FormGroup>
<FormGroup controlId="password">
<FormLabel>Password</FormLabel>
<FormControl
value={this.state.password}
onChange={this.handleChange.bind(this)}
type="password"
/>
</FormGroup>
<Button type="submit">Sign up!</Button>
</form>
</div>
);
}
}
最佳答案
你得到 404 是因为你没有在 Node 服务器中创建 POST 路由
所以你应该把它放在你的代码中
app.post("/createaccount", (req, res) => {
});
请让我知道我是否正确
关于javascript - ReactJS 和 Express with Axios 返回 404 错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56199245/