A
A
Alexey Yakovlev2021-01-17 16:41:18
Node.js
Alexey Yakovlev, 2021-01-17 16:41:18

How to send JSON data to client?

HTML:

<form className="header__search-form" onSubmit={() => search()} action="/search" method="POST">
                        <span>Поиск</span>
                        <input type="text" className="header-search-input" name="q" />
                    </form>


search function:
async function search() {
        const {data} = await axios.post('/search');
                  
        setProducts(data);
    }


Render on the server:
router.post('/', (req, res) => {
    product.find(async(err, data) => {
        if (err) res.status(400).send(err);
        else {
            if (req.body.q) {
                const newData = await data.filter(item => item.name.toLowerCase().search(req.body.q.trim().toLowerCase()) !== -1);
    
                res.status(200).send(newData);
            }
        }
    })
})


output newData (JSON)

How do I get this data and send it to the client?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel, 2021-01-17
@PAVLIK_GYRA

router.post('/', (req, res) => {
{query} = req.body
    product.find(async(err, data) => {
        if (err) res.status(400).send(err);
        else {
            if (query) {
                const newData = await data.filter(item => item.name.toLowerCase().search(query.trim().toLowerCase()) !== -1);
    
                res.json(newData);
            }
        }
    })
})

I
Ivan Vishnevsky, 2017-05-13
@forgetable

Web Audio API, it has filters.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question