L
L
lebedev1122020-07-08 19:14:27
Node.js
lebedev112, 2020-07-08 19:14:27

Why am I getting a strange response on the front from the API?

I'm making a small application with React on the front and Node (Express) on the back.

Problem: I'm sending a GET/POST request to a backend. The result is completely different if you use Postman. With a GET request, it returns some statistics, not real data that came from the server
Where to dig? What is the problem? I don't even know how to google it.

Code on the front (a GET request is made by the button, the application is running on the port http://localhost:3000)

const App = () => {

  const sendRequest = async () => {
    const res = await fetch('/api/sendrequest')
    console.log(res)
  }

  return (
    <div className="App">
      <button onClick={sendRequest}>Send</button>
    </div>
  );
}

Previously, on the front, I proxy all requests to the local server localhost:5000
(I specify the proxy settings in package.json) Code on the back (the route is already connected correctly, when sending a request, the console explicitly registers the request, which it prints in the console)
"proxy": "http://localhost:5000"

router.get('/', async (req, res) => {
    try {
        console.log('[GET]')
        return res.status(200).send('All done!')
    } catch(e) {
        console.log('Server Error: ', e.message || e)
        return res.status(500).json({message: 'Server Error'})
    }
})

Code result when using Postman
5f05effa7bbcc223806854.png

Result at the front:
5f05f02f62a12813180174.png

What's wrong? What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
lebedev112, 2020-07-08
@lebedev112

I solved the problem, in the Node.js code it was necessary to send JSON
Instead , you need to And also parse the received JSON at the front
res.status(201).send('All done!')
res.status(201).json('All done!')

const res = await fetch('/api/sendrequest')
const data = await res.json()
console.log(data))

Thanks for the tip Alexey Yarkov.

A
Alexey Yarkov, 2020-07-08
@yarkov

What if console.log(await res.json())?

A
aidarDev, 2020-07-08
@aidarDev

const sendRequest = async () => {
    const res = await fetch('/api/sendrequest')
    const data = await res.json();
    console.log(data);
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question