简体   繁体   中英

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

Pretty new with NodeJS and Express but want to figure out it is possible to add new objects after loading api via client side. So in the first place it should load the api via server-side which contains the existing objects and output on the client side, and when that is loaded I want to add new objects that I post via server side. So the new posted object should be added added to the json.

Client Side

 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;

Server Side

 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); });

I didn't understand what you meant, but I think you want to add more objects to the list of posts, if so, use the following:

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

You can post directly in their 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}); };

They described this on their site. Further read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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