【发布时间】:2020-08-08 18:15:59
【问题描述】:
我正在使用 node/express、mysql 和 react 创建这个任务跟踪器应用程序。
现在我正在尝试将输入的任务发布到我的数据库中(我已经编写了发布路线并且它在邮递员中工作正常),但是当我尝试从 react 的前端提交表单时,我收到了这个错误:400(错误请求)和 SyntaxError: Unexpected token
我的节点服务器在 localhost 3000 上运行,而我的 react 应用程序在 localhost 3001 上运行,但我向 localhost 3000 添加了代理。
下面是我在react的src中的submitHandler代码
submitHandler = (event) => {
event.preventDefault() //to prevent page refresh
console.log(this.state)
fetch("https://localhost:3000/api/task", {
method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(this.state)
})
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.log(err))
}
下面是我的后端 POST 路由的写法
const db = require("../models");
module.exports = function(router) {
router.get("/api/tasks", (req, res) => {
db.Task.findAll({}).then(data => {
res.json(data);
});
});
router.post("https://localhost:3000/api/task", (req, res) => {
db.Task.create({
task: req.body
}).then(data => {
res.json(data)
}).catch(err => res.json(err))
})
}
我的 server.js 文件也在下面
const express = require("express");
const app = express();
const path = require("path");
const PORT = process.env.PORT || 3000;
const db = require("./models");
const cors = require('cors')
var corsOptions = {
origin: '*',
optionsSuccessStatus: 200,
}
app.use(cors(corsOptions))
app.use(express.static(path.join(__dirname, "build")));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.get("ping", function (req, res) {
return res.send("pong");
})
// app.get("*", function (req, res) {
// res.sendFile(path.join(__dirname, "build", "index.html"));
// })
require("./controllers/taskController")(app);
db.sequelize.sync().then(function() {
app.listen(PORT, () => {
console.log("Your API server is now on PORT:", PORT);
})
})
知道是什么导致了这个错误吗?
【问题讨论】:
标签: mysql node.js reactjs error-handling http-post