【问题标题】:Error when posting to my backend API from React form从 React 表单发布到我的后端 API 时出错
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 我尝试这样做,然后出现错误提示 404 not found
    • 404 表示服务器上不存在 URL。尝试使用 CURL 进行点击,看看是否成功。这样您就可以确定根本原因,无论是前端代码还是 API 代码。
    • 所以我编辑了我的帖子,实际上我不再收到 404 错误,但现在我收到 400 错误说请求错误?并且存在语法错误?但我看不出我的代码有什么问题@gautamits
    • 那肯定是 API 错误。尝试在 API 代码的每个步骤中使用一些调试器或控制台日志来检查它在哪里中断。
    猜你喜欢
    • 2015-10-20
    • 2019-07-29
    • 2019-06-14
    • 2021-06-30
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 2017-03-15
    • 2021-07-10
    相关资源
    最近更新 更多