1

So, I am trying to fetch my back end code and receive the json response from the API I am querying on the back-end. It is returning an object but, my json is either buried in it or not there. I can log the data in node, I just can't send it back. I have tried res-send, res-json and res-end. I'm not sure where I'm going wrong. Thank you for any help!

web app console response Response {type: "basic", url: "http://localhost:3003/father", redirected: false, status: 200, ok: true, ...}

Front-end javascript

 document.querySelector('.sub').addEventListener('click', function (e) {
 e.preventDefault()
 const wordSearched = document.querySelector('.word').value;
 fetch(`/${wordSearched}`)
 .then(function(answer) {
 console.log(answer);
 const number = answer.total_results;
 console.log(number);
 const tag = document.querySelector(".tagg").innerHTML = `The word 
 ${wordSearched} was used ${number} times!`;
 return tag
 })
 .catch(function(error) {
 console.log('😮 There has been a problem with the fetch operation: ', 
 error.message);
 })});

Back-end node.js

 const express = require('express');
 const app = express();
 const morgan = require('morgan');
 const fetch = require('node-fetch');
 app.use(express.static('\public'));
 app.use(morgan('short'));
 app.get('/:wordSearched', (req, res) => {
 let word = req.params.wordSearched;
 console.log(word);
 fetch(`https://api.esv.org/v3/passage/search/?q=${word}`, {
 headers: {
 'Authorization': 'Token kkkdddd88383' // API Token
 }
 })
 .then(function(response) {
 return response.json()
 })
 .then(function(myJson) {
 const number = myJson.total_results;
 console.log(number);
 res.send(myJson) //cant send number??
 })
 .catch(function(error) {
 console.log('😮 There has been a problem with the fetch operation: ', error.message);
 })
 });
 //local host
 app.listen(3003, () => {
 console.log('server is up on 3003');
 });
asked Oct 23, 2018 at 0:28
2

1 Answer 1

1

So I figured out my issue after reading the fetch documentation at https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch. I had to call:

 .then(function(response) {
 return response.json()
})

On my front-end as well. I had previously only called it on the back-end thinking is was json I was sending. Unless I made the .json() call on each end I was not going to get my answer through.

answered Oct 23, 2018 at 1:08
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.