簡體   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