从React表单发布到我的后端API时出错



我正在使用node/express、mysql和react创建这个任务跟踪器应用程序。

现在我正试图将输入的任务发布到我的数据库中(我已经写好了发布路线,它在poster中运行良好(,但当我尝试从react的前端提交表单时,我收到了这个错误:400(错误请求(,SyntaxError:意外令牌<在JSON中的位置0 js:23

我的节点服务器在localhost3000上运行,而react应用程序在localhost3001上运行,但我向localhost3000添加了一个代理。

下面是我在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);
})
})

知道是什么导致了这个错误吗?

SSL错误通常发生在处理https://时。用http://替换所有出现的https://,这可能会在开发时解决您的问题。

最新更新