Node.js res.json() and res.send(), not working but still able to change status code

clock icon

asked 304 days ago Votes

message icon

2 Answers

eye icon

277 Views

I've read almost every thread about this and still can't figure out what's wrong.

Any information, either by res.send(), res.json(), res.write() res.end(), doesn't get received on the client side. But I know the info is getting sent and stored because the database is updating, and I know there is a response because I can console.log the object and if I change the server's status code (200 vs 201, for example) the response printed on the client side reflects that.

The client sends the email by post to the server.

var object = JSON.stringify({
      email: myemail,
    });
    await fetch('http://localhost:4000/api/subscriber/', {
      method: 'POST',
      body: object,
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => {
      res.json();
    console.log(res);})
    .then(response => console.log('Success:', response))
    .catch(error => console.error('Error:', error));

When I run this, these are the logs:

Response {type: "cors", url: "http://localhost:4000/api/subscriber/", redirected: false, status: 201, ok: true, …}

Success: undefined

Here's the relevant server side code

Path calls a function

app.post('/api/subscriber/', (request, response) => {
   db.createSubscriber(request, response);
   })

I've read almost every thread about this and still can't figure out what's wrong.

Any information, either by res.send(), res.json(), res.write() res.end(), doesn't get received on the client side. But I know the info is getting sent and stored because the database is updating, and I know there is a response because I can console.log the object and if I change the server's status code (200 vs 201, for example) the response printed on the client side reflects that.

The client sends the email by post to the server.

var object = JSON.stringify({
      email: myemail,
    });
    await fetch('http://localhost:4000/api/subscriber/', {
      method: 'POST',
      body: object,
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => {
      res.json();
    console.log(res);})
    .then(response => console.log('Success:', response))
    .catch(error => console.error('Error:', error));

When I run this, these are the logs:

Response {type: "cors", url: "http://localhost:4000/api/subscriber/", redirected: false, status: 201, ok: true, …}

Success: undefined

Here's the relevant server side code

Path calls a function

app.post('/api/subscriber/', (request, response) => {
   db.createSubscriber(request, response);
   })

Then the info is stored in the database and the response is sent. Here's where the problem is -- anything I try to send here -- even random text doesn't show up, but I know the communication is happening because I can see the status code logged from the client side when I change it.

 

2 Answers

It seems like the issue you are facing lies in how the response data is being processed on the client side. In your client-side code snippet, the issue is that you are not returning the parsed JSON response from the first `then()` block.

To properly handle the response from your fetch request, you should modify your client-side code as follows:

```javascript
var object = JSON.stringify({
email: myemail,
});

await fetch('http://localhost:4000/api/subscriber/', {
method: 'POST',
body: object,
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json()) // Return the parsed JSON response here
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));
```

By chaining `.then(res => res.json())`, you ensure that the response is properly parsed as JSON before moving on to the next `.then()` block where you log the successful response.

With this modification, you should be able to see the response data sent from the server logged in the console as expected when the POST request is successful.

It seems like the issue you are facing lies in how the response data is being processed on the client side. In your client-side code snippet, the issue is that you are not returning the parsed JSON response from the first `then()` block.

To properly handle the response from your fetch request, you should modify your client-side code as follows:

```javascript
var object = JSON.stringify({
email: myemail,
});

await fetch('http://localhost:4000/api/subscriber/', {
method: 'POST',
body: object,
headers: {
'Content-Type': 'application/json'
}
})
.then(res => res.json()) // Return the parsed JSON response here
.then(response => console.log('Success:', response))
.catch(error => console.error('Error:', error));
```

By chaining `.then(res => res.json())`, you ensure that the response is properly parsed as JSON before moving on to the next `.then()` block where you log the successful response.

With this modification, you should be able to see the response data sent from the server logged in the console as expected when the POST request is successful.

 

Write your answer here

Top Questions