0

I have a nodejs server serving the dictionary-info a keyword. Fir example, if I type 'expensive', I get the text as JSON showing up when I go to the URL: http://localhost:7000/expensive. {"name":"expensive","meaning":"costing a lot of money","examples":["an expensive bottle of wine","keeping a horse is expensive"]}. This works in Postman as well.

I have a separate front-end project that has to call the above URL http://localhost:7000/{keyword} so that I get the JSON, when I go to http://localhost:3000. However, I am stuck using fetch. The following is the code. Please let me know where I am wrong(I don't get any error in the Chrome Console, but don't get the JSON text either):

 fetch(url, {
          mode: 'no-cors',
           // regular fetch option
           method: 'GET',

           // add reply for this fetch
           replyWith: {
               status: 200,
               body: 'Dictionary app',
               headers: {
                   'Content-Type': 'text/json'
               }
           }})
      //.then((resp) => resp.json())
      .then(function(res){
          console.log(res.text());

          //return res.text;
       })
      .catch(( error) => { console.log('error')});
Nishanth Reddy
  • 589
  • 2
  • 14
  • 27

1 Answers1

0

The replyWith feature is for mock responses. If you want the legtimate response try this:

let req = 'Dictionary app';
let resp;
fetch(url, {
  method: 'POST',
  body: req,
  headers:{
    'Content-Type': 'text/plain' //Be careful this is format for what you are sending not what you are receiving
  }
}).then((res) => res.json())
.then((data) => {resp = data;}) //Store the data
.catch((error) => {console.error('Error:', error)})
Suhas
  • 550
  • 4
  • 11