【发布时间】:2021-10-18 03:36:29
【问题描述】:
我是 react 和 node.js 的新手。我正在尝试做的是我制作了一个假服务器(在端口 5000 上运行),其 API(http://localhost:5000/getData)具有对象的 harcode 值数组。现在我想从反应前端(在端口 3000 上运行)在 API(http://localhost:5000/getData)中添加新对象。为此,我正在使用 axios 的帖子,但是当我尝试添加新对象时,它给了我这样的错误:
有点困惑为什么它是这样的,我认为我做的一切都是正确的? 我附上相关代码。
server.js
const express = require("express");
const app = express();
const cors = require('cors')
app.use(cors({
origin: 'http://localhost:3000'
}))
// Routes
app.get('/getData', (req, res) => {
res.json([
{
"description": "",
"durationday": "fullday",
"end": "null",
"id": 0,
"location": "",
"start": "null",
"title": "",
},
{
"description": "yaaa!",
"durationday": "absent",
"end": "10-04-2021 12:10:00",
"id": 1,
"location": "perth",
"start": "10-04-2021 12:10:00",
"title": "holiday",
},
{
"description": "busy",
"durationday": "fullday",
"end": "10-22-2021 12:10:00",
"id": 2,
"location": "melbourne",
"start": '10-19-2021 12:00:00',
"title": "working",
},
{
"description": "dd",
"durationday": "halfday",
"end": "10-24-2021 12:10:00",
"id": 3,
"location": "updated perth",
"start": "10-24-2021 12:10:00",
"title": "updated holiday",
}
]);
});
app.listen(5000, () => console.log("Running on pot 5000"))
反应 axios 函数
const sendData = async () => {
const post = await axios.post('http://localhost:5000/getData', {
description: "dd",
durationday: "halfday",
end: "10-24-2021 12:10:00",
id: parseInt(344444),
location: "updated perth",
start: "10-24-2021 12:10:00",
title: "updated holidayssssssssss",
}
)
.then((response) => console.log(response.data))
.catch((error) => console.log(error));
return post;
}
点击按钮
<button onClick={sendData}> button post</button>
【问题讨论】:
标签: javascript node.js reactjs axios httprequest