I'm trying to display a content on my browser as JSON file using the following code
const express = require ("express")
const app = express();
app.get("/test", async(req, res) => {
const rows = await actiondb();
res.setHeader("content-type", "application/json")
res.send(JSON.stringify(rows))
})
Even using the setheader and "content-type", "application/json" it is not working. The photo below shows the results
I was expecting to get something as:
What can be done?
Your browser doesn't natively format JSON responses like you're showing in your example. If you want to format the JSON response in your browser, the browser extension JSON Formatter can be installed into your browser. This will detect JSON/JSONP and display it for you formatted.
Example with the extension installed:
All this extension does is make the JSON response easier to read, it doesn't change the content type or data returned. Making a request to /test will work with or without the extension.
As a side-note, your code can be simplified to use express's .json() method:
const express = require ("express");
const app = express();
app.get("/test", async(req, res) => {
const rows = await actiondb();
res.json(rows);
});
Related
I'm building an appplication using react at the front and express at the back in order to avoid cors issues. From the back I get the Json of my API from "Zoho Creator". Here an example.
As you can see I get a Json object, but in the image value, the URL appear without https://zoho.creator.eu... and when I try to request them from my frontend I can't render them. and if I add https://... at the beginning manually I get an error 401. I also tried to add the https route from the backend but is the same thing.
Here my backend using express
PD: I'm a rookie I know, please don't judge me.
const express = require("express")
const app = express()
const fetch = require("node-fetch")
const bodyParser = require("body-parser");
const cors = require("cors")
const PORT = process.env.PORT || 4000;
app.use(bodyParser.json());
const urlPost = ("https://accounts.zoho.eu/oauth/v2/token?refresh_token=1000.3dbdad6937dc0800c4dcc662cd14d173.86efb18e337989bebb3ff4c05582c94c&client_id=1000.NQL17JHK3Y62Y178TO0E3FQC6MBQJV&client_secret=5d04ad135862e7313377484af55efa1f41c1f49a39&grant_type=refresh_token")
const urlGet = "https://creator.zoho.eu/api/v2/hostienda1/Product-Catalog/report/Product_Details";
app.use(cors())
app.get
const peticion = fetch(urlPost,{
method: 'POST',
redirect: 'follow'
});
peticion
.then((ans)=>{return ans.json()})
.then((resp)=>{
const reslt = resp.access_token;
return app.get("*", async (req,res)=>{
const response = await fetch(urlGet,{
method: "GET",
headers:{
'Authorization':`Zoho-oauthtoken ${reslt}`,
}})
const result = await response.json()
const test = result.data
test.map(function(product){
if (true){
product.Product_Images[0] = "https://creator.zoho.eu" + product.Product_Images[0].display_value
return product.Product_Images[0]
}
})
res.json(test)
})
})
app.listen(PORT, () => {console.log(`Listening on port ${PORT}`)})`
I hope to render my images from my frontend app.
I assume that the download link for the image also requires authentication, in other words, the download requires a request like
GET https://creator.zoho.eu/api/v2/hostienda1/Product-Catalog/report/Product_Details/...jpg
Authorization: Zoho-oauthtoken ...
Such a request cannot be made your frontend, because it does not know the Zoho-oauthtoken.
This means that you must make this request in your backend. Rewrite your middleware so that it retrieves the download link for one image only (currently you return test, which contains many images). Then use the following code to access the image at that download link and return it to the frontend:
var img = await fetch("https://creator.zoho.eu/api/v2/...", // the download link
{headers: {authorization: `Zoho-oauthtoken ${reslt}`}}
);
res.set("content-type", img.headers.get("content-type"));
stream.Readable.fromWeb(img.body).pipe(res);
This is my function
export const testFunction = functions.https.onRequest((req, res) => {
const text = req.body.text;
res.set("Access-Control-Allow-Origin", "*");
res.send({text: text});
});
i've tried using const cors = require('cors')({origin: true});
I keep getting this as a response. Does anyone know why?
Consider importing like this,
const cors = require('cors')({origin: true});
And try running the below function using firebase deploy –only functions :
const functions= require("firebase-functions");
const cors = require('cors')({origin: true});
exports.testFunction = functions.https.onRequest((req, res) => {
cors(req, res, () => {
const text = req.body.name;
res.send({text:text});
});
});
And then send request using :
curl -X POST "https:/region-projectID.cloudfunctions.net/function-name" -H "Content-Type:application/json" --data '{"name":"Keyboard Cat"}'
The output I am getting in the console is :
And when I click on the Cloud Function URL endpoint, my output is an empty {}.
If you try res.send(“Hello World”) in place of res.send({text:text}), you will get the output in the browser as Hello World but since our Cloud Function performs some contrived operation using data passed in the request body.This could result in an error at run time if the property name is null or undefined.
And indeed, if we deploy this new function and then attempt to call it from our web app without updating our request we do get an error. However, it might not be the error you’d expect.
It’d be easy to assume that we somehow misconfigured our CORS policy. Infact swapping cors() to cors({ origin: '*'}) to cors({ origin: true}) all to no avail. Only when we view the logs for our Cloud Function do we get a useful error message.
So try sending a POST request with the –data flag, or if you are using Postman, send the data and the parameters. Then only you would be able to have an output, if you still see the CORS error, check if your function is handled well or your nested request body attribute is not undefined/null. Sometimes CORS errors are not always CORS!
I'm learning node.js currently and I'm stuck with this problem. I was able to successfully create my node.js server and it works when I run it on the terminal. I even console.log the data I am trying to GET and it shows in the terminal but when I try to load it on Postman, it doesn't show anything.
I use localhost:9001/api but it doesn't load. I don't even get any errors.
Here's my code:
const express = require('express');
const app = express();
const fetch = require('node-fetch');
require('dotenv').config();
const api_key = XXXXXXXXXXX
app.use(express.static('public'));
app.listen(9001, () => console.log('listneing at 9001'));
app.get("/api", async (req,res)=> {
console.log("getting data")
const url = `website.com/vi/api/?alt=json&key=${api_key}`
const options={
"method" : "GET"
};
const response = await fetch(url, options)
.then(response => response.json())
.catch(e => {
console.errror({
"message": "oh no",
error : e,
});
});
console.log(response)
});
Not sure how to solve it can anyone please help a new learner? 🙏
Postman needs a response from your side to show Responses.
The console.log() prints the output on your screen but in order to get response in Postman, You have to return a response like
return res.status(response.code).json(response);
This is my way of returning response. You can make your own variable and add values to them.
So I'm trying to learn nodeJS.. But something wierd is happening. When I try to make a GET or a POST request it keep requesting infinitly on the localhost. I tested with a simple piece of code just requesting a simple Hello Word but it still doesnt works. It was working perfectly yesterday.
I tested insomnia, postman and the browser. If someone can help me would be very nice, cause I'm really stucked here...printscream of the insomnia infinity request
const {json} = require('express');
const express = require('express');
const {uuid} = require('uuidv4');
const app = express();
app.use(express,json);
const projects = [];
app.get('/projects', (request, response) => {
return response.json(projects);
});
app.post('/projects', (request, response) => {
const {title, owner} = request.body;
const project = {id: uuid(), title, owner };
projects.push(project);
return response.json(project);
});
app.listen(3333, () => {
console.log('Working 👏👏')
});
It's just two little mistakes. Take in mind that express.json() is a method, so you need to put it like this:
app.use(express.json())
You are using a comma instead of a point. However, you have done a destructuring of the .json () method; therefore, you do not have to prepend express; it would look like this:
app.use(json())
On the other hand, you probably have an unwanted result in the post request since you send the project variable instead of projects. Be sure that is what you want.
I'm trying to do a POST request using raw json.
In the Body tab I have "raw" selected with this body:
{
"name": "book"
}
On the Node js side I'm doing res.send(JSON.stringify(req.body))
router.post('/', (req, res, next) => {
res.send(JSON.stringify(req.body));
}
And in POSTMAN response I receive:
{"{\n\"name\": \"book\"\n}":""}
When expected something like
{"name":"book"}
Have no idea - where could be a reason for it?
You'll need to use the Express JSON body parser, install using
npm install body-parser;
Then:
const bodyParser = require('body-parser');
app.use(bodyParser.json());
Once you do this, the JSON data will be parsed correctly and when you send it back it will render correctly.
Also make sure you have your Content-Type header set to "application/json" in your Postman request (go to "Headers" and add a new "Content-Type" header with value "application/json")
Here's a simple express app that will echo any JSON POST:
const express = require("express");
const port = 3000;
const app = express();
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post('/', (req, res, next) => {
console.log("Body: ", req.body);
res.send(JSON.stringify(req.body));
})
app.listen(port);
console.log(`Serving at http://localhost:${port}`);
If you're on Express v4.16.0 onwards, try to add this line before app.listen():
app.use(express.json());
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
Looks to me like its not a fault of Postman, but your NodeJS service is applying JSON.stringify twice?
Can you log the response type from the server to console to check whether its already json content or not?
try with hard coded json response and then with dynamic variable
res.json({"name":"book"});