how to handle values other than json in fetch api call

Viewed 611
I want to send json data to API AND GET A STRING VALUE WILL IT BE POSSIBLE 

I have a node js API which return a value(not json type):

res.send(code);

in reactjs i am using fetch api in the following way,

  const options = {
  method: "POST",
  headers: {
    "Content-Type": "application/json"

  },
  body: JSON.stringify({ url: this.state.url })
};

fetch("http://localhost:3000/messages", options)
  .then(response => response)
  .then(data => {
    console.log(data)
    this.setState({ code: data.code });
  });

but i am getting an error as

localhost/:1 Uncaught (in promise) SyntaxError: Unexpected token h in JSON at position 0

i know i am getting this error as i am not passing json from the api can u help me solve this error the code in node api

        const express = require("express");
          const app = express();
         const cors = require("cors");
            const shorten = require("../../task1/src/shorten");
          const fs = require("fs");
           app.use(cors()); // to send CORS headers.
             app.use(express.urlencoded()); 
            app.use(express.json()); // to support JSON-encoded bodies.
           const fileName = "urldata.json";

             var write = (shortcode, urlData, url) => {
                 console.log(shortcode + ":::in writing");
                var shortcode = shortcode;
                  urlData.urlcodes.push({
                          url: url,
                      shorten: shortcode
                            });

           fs.writeFileSync(fileName, JSON.stringify(urlData), (err, data) 
        => {
          if (err) console.log(err);
          console.log("written in bdy");
             });
             };

                  var filecheck = (urlData, url, shrtcd) => {
                   {
             if (!shrtcd) {
  shortcode = shorten(url);
  write(shortcode, urlData, url);
  return shortcode;
     } else {
  write(shrtcd, urlData, url);

  return shrtcd;
        }
      }

          for (var i = 0; i < urlData["urlcodes"].length; i++) {
if (urlData["urlcodes"][i].url === url) {
  shortcode = urlData["urlcodes"][i].shorten;
  return shortcode;
            } else continue;
            }
         };

       app.post("/shortcodes", function(req, res) {

          console.log(req.body)
              if (!fs.existsSync(fileName)) {
                 const data = { urlcodes: [] };
                fs.createWriteStream(fileName, "utf-8");
                  fs.writeFile(fileName, JSON.stringify(data), err => {
                        console.log(err);
                       });
                          }
             fs.readFile(fileName, "utf-8", (err, data) => {
                if (err) console.log(err);
              var urlData = JSON.parse(data);

              var code = filecheck(urlData, req.body.url, req.body.shortcode);

          res.send(code); 
                });
               });
2 Answers

Please modify your header:

{headers: {"Content-Type": "text/plain"}}

for parsing nested objects in req body you need to do something like this:

app.use(bodyParser.urlencoded({ extended: true }));

This would solve the issue. Let me know if it doesn't work

"Content-Type": "application/json"

This is used for content-negotiation between client & server. This tells server if you are sending the JSON and accepting the response in the same format.

Now as you are asking for json negotiation so the server will try to parse the body as json and process the same.

In your case, you body data which you are sending is not valid JSON properly.

I would suggest you to log the body value and validate it with json validator (https://jsonformatter.curiousconcept.com/) and fix the changes suggested by the tool and try again.

Changing content-Type will not help till your server support it.

I hope it helps.

Related