正在获取 404 AxiosError: 请求失败, 状态代码 404
原标题:Getting 404 AxiosError: Request failed with status code 404
Could you please help me to solve the problem with the routes.
In result I have the next code:
// server/index.js
// server/index.js
const express = require( express );
const bodyParser = require( body-parser );
const cors = require( cors );
const authRoutes = require( ./routes/auth );
const userRoutes = require( ./routes/users );
const abiturientRoutes = require( ./routes/abiturients ); // Добавили
const app = express();
const PORT = 5000;
// Middleware
app.use(cors());
app.use(bodyParser.json());
// Маршруты
app.use( /api/auth , authRoutes);
app.use( /api/users , userRoutes);
app.use( /api/abiturients , abiturientRoutes); // Добавили
// Запуск сервера
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Then I got the following code
//server/routes/abiturients.js
//server/routes/abiturients.js
const express = require( express );
const router = express.Router();
const pool = require( ../db/connection );
// Получение всех абитуриентов
router.get( / , async (req, res) => {
try {
const [rows] = await pool.query( SELECT * FROM abiturients );
res.json(rows);
} catch (err) {
console.error(err);
res.status(500).json({ message: Error fetching abiturients });
}
});
// Создание нового абитуриента
router.post( / , async (req, res) => {
const { full_name, gender, recommended_by, education_level, available_specialty, previous_educational_institution, phone_number, date_added, desired_education_level, desired_specialty, specialization, study_form, student_status, notes, questionnaire_date, gunp_call_date, document_submission_date, medical_commission_completion_date, vlk_start_date, vlk_end_date, evi_efvv_registration_date, documents } = req.body;
try {
const sql = `
INSERT INTO abiturients (
full_name, gender, recommended_by, education_level, available_specialty,
previous_educational_institution, phone_number, date_added,
desired_education_level, desired_specialty, specialization, study_form,
student_status, notes, questionnaire_date, gunp_call_date,
document_submission_date, medical_commission_completion_date,
vlk_start_date, vlk_end_date, evi_efvv_registration_date, documents
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`;
const [result] = await pool.query(sql, [
full_name, gender, recommended_by, education_level, available_specialty,
previous_educational_institution, phone_number, date_added,
desired_education_level, desired_specialty, specialization, study_form,
student_status, notes, questionnaire_date, gunp_call_date,
document_submission_date, medical_commission_completion_date,
vlk_start_date, vlk_end_date, evi_efvv_registration_date, documents
]);
res.status(201).json({ id: result.insertId });
} catch (error) {
console.error( Error adding abiturient: , error);
res.status(500).json({ message: Error adding abiturient });
}
});
// Обновление абитуриента по ID
router.put( /:id , async (req, res) => {
const {
full_name, gender, recommended_by, education_level, available_specialty,
previous_educational_institution, phone_number, date_added,
desired_education_level, desired_specialty, specialization, study_form,
student_status, notes, questionnaire_date, gunp_call_date,
document_submission_date, medical_commission_completion_date,
vlk_start_date, vlk_end_date, evi_efvv_registration_date, documents
} = req.body;
const { id } = req.params;
try {
const sql = `
UPDATE abiturients SET
full_name = ?, gender = ?, recommended_by = ?, education_level = ?, available_specialty = ?,
previous_educational_institution = ?, phone_number = ?, date_added = ?,
desired_education_level = ?, desired_specialty = ?, specialization = ?, study_form = ?,
student_status = ?, notes = ?, questionnaire_date = ?, gunp_call_date = ?,
document_submission_date = ?, medical_commission_completion_date = ?,
vlk_start_date = ?, vlk_end_date = ?, evi_efvv_registration_date = ?, documents = ?
WHERE id = ?
`;
const [result] = await pool.query(sql, [
full_name, gender, recommended_by, education_level, available_specialty,
previous_educational_institution, phone_number, date_added,
desired_education_level, desired_specialty, specialization, study_form,
student_status, notes, questionnaire_date, gunp_call_date,
document_submission_date, medical_commission_completion_date,
vlk_start_date, vlk_end_date, evi_efvv_registration_date, documents, id
]);
res.status(200).json({ message: Abiturient updated successfully });
} catch (error) {
console.error( Error updating abiturient: , error);
res.status(500).json({ message: Error updating abiturient });
}
});
// Удаление абитуриента по ID
router.delete( /:id , async (req, res) => {
try {
await pool.query( DELETE FROM abiturients WHERE id = ? , [req.params.id]);
res.json({ message: Abiturient deleted successfully });
} catch (err) {
console.error(err);
res.status(500).json({ message: Error deleting abiturient });
}
});
module.exports = router;
//src/services/api.js
//src/services/api.js
import axios from axios ;
const API_URL = http://localhost:5000 ;
export const fetchAbiturients = () => {
return axios.get(`${API_URL}/abiturients`); // исправленный синтаксис
};
export const createAbiturient = (abiturient) => {
return axios.post(`${API_URL}/abiturients`, abiturient); // исправленный синтаксис
};
export const updateAbiturient = (id, abiturient) => {
return axios.put(`${API_URL}/abiturients/${id}`, abiturient); // исправленный синтаксис
};
export const deleteAbiturient = (id) => {
return axios.delete(`${API_URL}/abiturients/${id}`); // исправленный синтаксис
};
I have the following error:
ERROR
Request failed with status code 404
AxiosError: Request failed with status code 404
at settle (http://localhost:3000/static/js/bundle.js:122693:12)
at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:121359:66)
at Axios.request (http://localhost:3000/static/js/bundle.js:121846:41)
问题回答
const API_URL = http://localhost:5000
Your backend endpoint is http://localhost:5000/api/abiturients
`${API_URL}/abiturients` -> This returns http://localhost:5000/abiturients
You are making request to http://localhost:5000/abiturients which does not exists
Update API URL variable with /api then you will be able to make requests
const API_URL = http://localhost:5000/api