我正在使用node / express,mysql和react创建此任务跟踪器应用。
现在,我试图将输入的任务发布到我的数据库中(我编写了发布路线,并且在邮递员中可以正常工作),但是当我尝试从react的前端提交表单时,出现此错误: 400(错误请求)和SyntaxError:意外的令牌
我的节点服务器在本地主机3000上运行,而我的应用程序在本地主机3001上运行,但我向本地主机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);
})
})
任何想法导致此错误的原因是什么?
SSL错误通常在您处理https://时发生。用http://替换所有https://的出现,这可能会在开发过程中解决您的问题。