NodeJS express restapi无法按预期工作尝试发布时出现500或400服务器错误[已关闭]

tpxzln5u  于 2023-03-01  发布在  Node.js
关注(0)|答案(1)|浏览(138)

**已关闭。**此问题需要debugging details。当前不接受答案。

编辑问题以包含desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem。这将有助于其他人回答问题。
1小时前关闭。
Improve this question
这是我的server.js和user.js当我试图将答案发布到服务器时,我得到了错误500。我不知道我应该如何进一步解决这个代码。我想知道这是我的查询还是发送到服务器的json的问题。我还添加了body-parser,并重做了表模式,使其与我的代码更相关。

import React, { useState, useEffect } from "react";
import axios from "axios";

const QuestionAnswerForm = () => {
  const [question, setQuestion] = useState("");
  const [answer, setAnswer] = useState("");
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Fetch a random question from the database
    axios.get("http://localhost:5000/questions").then((response) => {
      const randomIndex = Math.floor(Math.random() * response.data.length);
      setQuestion(response.data[randomIndex]);
      setLoading(false);
    });
  }, []);

  const handleSubmit = (e) => {
    e.preventDefault();
    axios
      .post("http://localhost:5000/answers", { question, answer })
      .then((response) => {
        console.log(response.data);
        // Reset the form after submitting the answer
        setAnswer("");
        setLoading(true);
      });
  };

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h2>{question.title}</h2>
      <p>{question.description}</p>
      <form onSubmit={handleSubmit}>
        <label htmlFor="answer">Your answer:</label>
        <input
          type="range"
          id="answer"
          name="answer"
          min="1"
          max="5"
          value={answer}
          onChange={(e) => setAnswer(e.target.value)}
        />
        <output htmlFor="answer">{answer}</output>
        <button type="submit">Submit</button>
      </form>
    </div>
  );
};

export default QuestionAnswerForm;

const express = require('express')
const mysql = require('mysql2/promise');
const pool = require('./db.js');
const cors = require("cors");
require("dotenv").config();

const corsOptions = {
  origin: ['http://localhost:3000']
}
const app = express();
const port = process.env.PORT || 5000;
app.use(cors(corsOptions));
app.use(express.json()); // for parsing application/json
app.use(express.urlencoded({ extended: true }));

app.get('/questions', async (req, res) => {
  try {
    const connection = await mysql.createConnection({
      host: process.env.DB_HOST,
      user: process.env.DB_USER,
      password: process.env.DB_PASSWORD,
      database: process.env.DB_DATABASE
    });

    const [rows] = await connection.execute('SELECT * FROM questions');
    res.json(rows);

    await connection.end();
  } catch (err) {
    console.error("Unable to retrieve data from database", err);
    res.status(500).json({ error: 'Unable to retrieve data' });
  }
});

app.post('/answers', async (req, res) => {
  try {
    const { questionId, answer } = req.body;

    if (!questionId) {
      return res.status(400).send('questionId is required');
    }

    // Check that answer is a valid number
    if (isNaN(answer)) {
      return res.status(400).send('answer must be a number');
    }

    const con = await pool.getConnection();
    await con.query('INSERT INTO answers (question_id, answer_text) VALUES (?, ?)', [questionId, answer]);
    con.release();
    return res.send('Answer submitted successfully!');
  } catch (error) {
    console.error(error);
    return res.status(500).send('Internal server error');
  }
});

app.listen(port, () => {
  console.log(`Server started on port ${port}`);
});

Iv尝试添加body-parser,重做数据库表模式,并更改所使用的查询,但似乎都不起作用。

yx2lnoni

yx2lnoni1#

也许在你的axios文章中设置一个标题,'Content-Type':“application/json”将修复此问题。

相关问题