How to send API response through body with node.js? - javascript

So I have an API that works fine and responds as I need, but I was wondering how I would set the response from the API to be in the body?
Right now it's just setting the response to be in a <pre> tag on the actual website (if I inspect element it shows like below):
<body><pre>{api response}</pre></body
but the only way I can access it is if it's in the body response.
If I check the console.log one the response, it just shows a bunch of blank spaces, so I was wondering how I would set up the API so it will respond in the body? Any help would be appreciated.
For the API I'm using Node.js with express and request packages if that helps at all

I'm not sure if i understand your question, but i'm sure that you can insert your response in any place you want. Try using jade or mustache (handlebars).

Here is the example from the Express website:
app.get('/', function (req, res) {
res.send('Hello World!')
})
This sends "Hello World!" in the HTTP response body.
So to send the API result instead you need to:
Set the appropriate content-type header
Send the result of getting stuff from the API
Such:
app.get('/', function (req, res) {
var api_response = get_data_from_api();
res.set('Content-Type', 'application/xml'); // or application/json or whatever
res.send(api_response);
})

Related

Request post return an empty object in NODE.JS

I don't know why but i try to send an object in my back. I can find good information in my network's payload but my req.body return everytime an empty object
my probleme
add app.use(express.json());
express.json() is a middleware that allows express to recognise the json data in request object.
Also your controller is not sending any response back, for that use:
app.post("/", (req, res) => {
res.status(200).json({"data" : req.body});
}

How to access req.body via expressjs?

I cant access body when getting expressjs request
My main server.js file
app.use(express.urlencoded({extended: true}));
app.use(express.json());
app.use(router);
My router.js file
const express = require("express");
const articlesContr = require("./../controllers/articlesContr.js");
const router = express.Router();
router
.get("/articles", articlesContr.handleGet)
.post("/articles", articlesContr.handlePost)
.put("/articles", articlesContr.handleUpdate)
.delete("/articles", articlesContr.handleDelete);
adminPanelContr.js
const controller = {
handleGet: (req, res) => {
const query = req._parsedUrl.query;
const parsedQuery = querystring.parse(query);
// res.send(productsDb.getItem(parsedQuery));
console.log(req)
res.send(JSON.stringify(req.body))
}
};
GET requests don't have body parameters. Ordinarily .get() handler functions don't look for them.
If you use the same handler function for GET and other (POST, PUT, PATCH, DELETE) requests, you need logic to avoid looking at the body when you get a GET.
When you send a request with a JSON body, don't forget to tell your server it's JSON by including a Content-Type: application/json HTTP header. That way you're sure express will invoke its express.json middleware to parse the body into the req.body object.
When you .get() a GET, you don't get a request body. There's gotta be some sort of doggerel poetry in there someplace.
If you use res.json(object) rather than res.send(JSON.stringify(object)) express does a good job of setting the HTTP response headers to useful values for JSON.
And, I'm sure you know this: Responding to a request with its own request body is a little strange.

javascript..when i do POST method ..it shows an space appending

coding image
output image
it showing a extra space when i do post method using REST API method
You are not parsing your data correctly. You need to POST the object as JSON.stringify(yourobject) and then have nodejs run jsonencoder to parse the data correctly, otherwise your request body will always be null. Below is an example.
var jsonencodedParser = bodyParser.json({ extended: false });
app.post('/test', jsonencodedParser, function (req, res) {
console.log('this is req.body');
console.log(req.body);
res.status(205)
res.send();
})//end function

How do I call a invoke an ajax get request from client side, using Node/Express?

I have a file shuffleRoute.js where I define this:
router.get("/shuffle?jokers=false", function (req, res) {
cards['a','b','c'];
let shuffledCards = _.shuffle(cards);
res.status(200).send(shuffledCards);
});
I have an index.js where I define:
app.get("/v1/game", require("./routes/shuffleRoute.js"));
I have a game.html where onload I need to do an ajax request to get the shuffled cards. How do I do that?
doing this
$.get( "/v1/game", function(res) {
console.log(res);
});
does not work.
I am getting this error:
jquery-2.2.4.min.js:4 GET localhost:8080/v1/game 500 (Internal Server Error) –
I was using morgan to log things in the server which was incorrectly done.
However, commenting that out gives me this error.
jquery-2.2.4.min.js:4 GET http://localhost:8080/v1/game 404 (Not Found)
May be wrong but i see routes problem here.
When you define routes for express use app.use
var myRoute = require('PathToYourRouteFile');
app.use("/v1/game", myRoute);
In route file. Im asuming you use express router you need to define something like this
youRuoterName.get('/', function(req, res, next) { })
This request will be succes when you go to localhost/v1/game.
If you want another one just do
youRuoterName.get('/shuffle', function(req, res, next) { })
Which will be succes when you go to /v1/game/shuffle.
In your example i see only one route /v1/game/shuffle which clearly not match /v1/game and im not even sure that rest of code works as expected.
So please read docs carefuly http://expressjs.com/en/4x/api.html#router.route
and all should work.
Hope this helps.

Specific url and parameter in Node.js project

I have 2 qeustions :
1. I want my project's url to be like 127.0.0.1:8080/param=id and I couldnt do it, I tried:
app.get('/param=id', function(req, res) {
console.log(req.param("id"));
});
if I write '/param/:id' it works but I dont want the url to look like this
I want my program to send message according to the id a json message or string to the client
So my second question is how the client gets the response - I want the message to go throgh a script in the client's side?
I would suggest using req.query instead of req.params:
app.get('/', function(req, res) {
console.log(req.query.id);
// or you may still use req.param("id")
});
requesting it like
HTTP GET 127.0.0.1:8080/?id=my_id
query is a different way of sending data to the server, designed to send key-value pairs.
Though, if id is the only thing you want to send to the server, I would recommend to stick with params, e.g.:
app.get('/:id', function(req, res) {
console.log(req.params.id);
});
requesting it like
HTTP GET 127.0.0.1:8080/my_id

Categories

Resources