Не получается отправить PUT запрос React
Добрый день и заранее спасибо.
Я пытаюсь вывести в консоль результат отправки Put запроса в React, но я не могу понять почему он не получает входные данные с input и данные с сервера о ошибке запроса.
Сервер на Node.js, база данных MongoDB
Вот функция получения с input значения, и в comment оно приходит
const handleSubmit = (event) => {
event.preventDefault();
dispatch(updateUserFinanceInfo({ comment }));
clearInput();
};
Вот компонент в React
<form onSubmit={handleSubmit}>
<label>
{commentDirty && commentError && (
<span
style={{
color: "red",
fontSize: 15,
paddingTop: 4,
}}
>
{errorSymbol}{" "}
</span>
)}
<p>Comment</p>
<input
onBlur={handleChange}
onChange={commentHandler}
type="text"
value={comment}
placeholder="Comment"
/>
</label>
<button type="submit">
<span>Smenit</span>
</button>
</form>
Вот так я отправляю запрос:
export const updateUserFinanceInfo = createAsyncThunk(
"auth/profile/update",
async (_, { credentials, rejectWithValue }) => {
console.log(credentials);
try {
console.log("credentials", credentials);
const { data } = await axios.put(
"auth/profile/update",
credentials
);
console.log("data", data);
return data;
} catch (error) {
console.log(error);
return rejectWithValue(error);
}
}
);
Но в credentials ничего не приходит, а значит req.body пустой.
Я пытаюсь вывести результат res с сервера Node.js но получаю:
TypeError: res.status is not a function
at Object.Update (helpers\statuses.js:65:20)
at updateUserFinanceInfo (asmis-new-bd\controllers\auth\userControllers.js:146:28)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async asmis-new-bd\middlewares\ctrlWrapper.js:4:7
Вот так выгдлядит мой контроллер:
const updateUserFinanceInfo = async (req, res, next) => {
try {
const data = await Repositories.findOneAndUpdate(
req,
req.user.workerId
);
if (!data) {
return Helpers.Conflict(
res,
Helpers.HttpCode.CONFLICT,
Helpers.Statuses.ERROR,
Helpers.Messages.AGAIN
);
} else {
return Helpers.Update(
Helpers.HttpCode.OK,
req,
res,
Helpers.Messages.UPDATED,
Helpers.Statuses.SUCCESS
);
}
} catch (error) {
next(error);
}
};
Вот так я отправляю на сервер данные:
const findOneAndUpdate = async (req, workerId) => {
try {
return await Auth.findOneAndUpdate(
{ workerId },
{ ...req.body },
{ new: true }
);
} catch (error) {
console.log(error);
}
};
Вот так я получаю res статусы - Успешный:
const Update = async (res, code, status, message, req) => {
try {
return res.status(code).json({
code,
status,
message,
data: {
...req.body,
},
});
} catch (error) {
console.log(error);
}
};
Отрицательный:
const Conflict = async (res, code, status, message) => {
try {
return res.status(code).json({
code,
status,
message,
});
} catch (error) {
console.log(error);
}
};
Вот так выглядит моя схема:
const joiUpdateSchema = Joi.object({
linkToPhoto: Joi.string(),
username: Joi.string().min(5),
name: Joi.string().min(3).max(15),
surname: Joi.string().min(3).max(15),
email: Joi.string().email().max(256),
phoneNumber: Joi.string().min(9).max(13),
language: Joi.string().valid(...lang),
theme: Joi.string().valid(...theme),
firm: Joi.string().min(2),
workingContractType: Joi.string().valid(...workingCategory),
comment: Joi.string(),
additionalColumn: { workerInfo: Joi.string() },
});
Вот так я отправляю на сервер запрос:
router.put(
"/profile/update",
auth,
validation(Schema.joiUpdateSchema, "Try it again"),
ctrlWrapper(ctrl.updateUserFinanceInfo)
);
Вот так выглядит app.js на сервере
const authRouter = require("./routes/api/auth");
const app = express();
const formatsLogger = app.get("env") === "development" ? "dev" : "short";
app.use(logger(formatsLogger));
app.use(cors());
app.use(express.json());
app.use(express.static("public"));
app.use("/api/auth", authRouter);
app.use((req, res) => {
res.status(HttpCode.NOT_FOUND).json({
code: HttpCode.NOT_FOUND,
message: "Not found",
});
res.status(HttpCode.BAD_REQUEST).json({
code: HttpCode.BAD_REQUEST,
message: "Bad request",
});
});
app.use((err, req, res, next) => {
const {
status = HttpCode.INTERNAL_SERVER_ERROR,
message = "Server error",
} = err;
res.status(status).json({ message });
});
module.exports = app;
Источник: Stack Overflow на русском