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);
});
});