繁体   English   中英

如何将新的 object 发布到现有的 json(客户端 ReactJS + 服务器端 NodeJS 和 Express)

[英]How to post new object to the existing json (clientside ReactJS + server side NodeJS and Express)

NodeJS 和 Express 相当新,但想弄清楚在通过客户端加载 api 后可以添加新对象。 因此,首先它应该通过服务器端加载 api,其中包含现有对象和客户端的 output,当加载时我想添加我通过服务器端发布的新对象。 所以新发布的 object 应该添加到 json 中。

客户端

 import { useEffect, useState } from 'react'; import axios from 'axios'; export const App = () => { const [inputValue, setInputValue] = useState(""); const [posts, setPosts] = useState([]); useEffect(() => { const headers = { "Content-Type": "application/json" }; try { const getData = async () => { const result = await axios.get('http://localhost:5000', headers); console.log(result.data); }; getData(); } catch (error) { console.log(error); } }, []); const postReview = async value => { const headers = { "Content-Type": "application/json" }; let data = { name: value }; try { const getData = async () => { const result = await axios.post('http://localhost:5000/songs', data, headers); console.log(result.data); }; getData(); } catch (error) { console.log(error); } }; const submitReview = () => { postReview(inputValue); }; return ( <div className="App"> <input placeholder="Place review" onChange={e => setInputValue(e.target.value)} /> <button onClick={() => submitReview()}>Send</button> </div> ); }; export default App;

服务器端

 const express = require('express'); const cors = require('cors'); const axios = require('axios'); const app = express(); const port = 5000; app.use(cors({ origin: '*' })); app.use(express.json()); app.get("/", async (req, res, next) => { try { const { data } = await axios.get('https://raw.githubusercontent.com/XiteTV/frontend-coding-exercise/main/data/dataset.json'); res.status(200).send(data.videos); } catch (ex) { res.status(500).send(data.videos); } }); app.post('/songs', async (req, res) => { console.log(reviews.length); });

我不明白你的意思,但我认为你想在帖子列表中添加更多对象,如果是这样,请使用以下内容:

setPosts([
   ...posts,
   {
      //New post object
   }
])

您可以直接在他们的 API 中发布。

 const postReview = async review => { const headers = { "content-type": "application/json", "Access-Control-Allow-Origin": "*" }; // axios post request to that api const response = await axios.post('https://jsonplaceholder.typicode.com/posts', {review}, {headers}); };

他们在他们的网站上描述了这一点。 进一步阅读

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM