node-rest-client POST Vs. PUT - node.js

Has anyone used node-rest-client? For POST and PUT methods, it says "To send data to remote site using POST or PUT methods, just add a data attribute to args object:" So how can I distinguish between a POST call and PUT call?

To make a put request, you just use the put method instead of the post or get methods.
client.put("http://remote.site/rest/xml/method", function(data, response){
// parsed response body as js object
console.log(data);
// raw response
console.log(response);
});

Related

Node.js Export and use post request in another command line script

i have a problem which i think it's a basic yet couldn't figure it out. I have a post request in a js file and i export it to app.js. And i have another js file which will be executed as command line script only. What i want is; using the same post internally by sending the body. I want to call the post and get the response in this file. Here is my code;
Customers.js;
router.post('/', async (req, res) => {
//some work
res.status(201).send(v_return);
});
module.exports.router = router;
Command-line.js;
const customer = require('./routes/customers')
//..some irrelevant code
//this is what i've tryed, i need to send cust[0] as req body
var res = customer.router.use(function(req,res){
req.body=cust[0];
});
console.log(res); //i need the response
//..some irrelevant code
Basically i need to make the post with v_cust[0] as body. And get the response. Thanks in advance.
EDIT: I've create seperate function that takes body and do the work. Then i used it both post and command-line script. So i have a solution but still i don't know if i can make post request in the api. If there is an answer for it, i would appreciate it.

Scrapy - is it possible to extract Payload Request from Response

is it possible to extract and set as variable the "Payload Request" which has been pushed in order to receive particular response?
You can access the request object in the callback function by response.request.
This object is the request object itself, so it contains everything you passed in the request. It doesn't have a "payload" attribute though.
The equivalent should be response.request.body, assuming you had a body in the request. Everything else is still there, headers, cookies, meta, method, etc
More on the params of request here.

Why does my express router crash only when i send a JSON and not when i send a text ?

statusRouter.route('/')
.all(function(req,res,next){
res.writeHead(200, {'Content-Type': 'application/json'});
next();
})
.get(function(req, res, next) {
res.json({
name : "xyz"
});
});
This crashes with - Header cant be set after it has been sent.
But the catch is , this works :
statusRouter.route('/')
.all(function(req,res,next){
res.writeHead(200, {'Content-Type': 'text/plain'});
next();
})
.get(function(req, res, next) {
res.end("xyz");
});
NOTE : If I remove the writeHead function in the first case where I am sending JSON it starts working as well. Why does it not work when i do a writeHead on it ? This thing is driving me crazy can anyone explain why this happens ?
P.S I'm working with express-generated app with my own router.
Both res.writeHead() and res.end() are not implemented by Express, but by the Node.js http module.
Its documentation states, for res.end():
If data is specified, it is equivalent to calling response.write(data, encoding) followed by response.end(callback)
So res.end("xyz") is short for:
res.write("xyz");
res.end();
For res.write() the documentation states:
If this method is called and response.writeHead() has not been called, it will switch to implicit header mode and flush the implicit headers.
So res.end("xyz") is actually short for:
if (! res.headersSent) {
res.writeHead(...);
}
res.write("xyz");
res.end();
This means that it's perfectly okay to issue res.writeHead() in your own code, before using res.end(). Internally, the http module will know that you already flushed the headers, so it won't do it again (therefore preventing the error you're getting). However, you can't set different headers, or change existing ones, once writeHead() has been called.
Now, res.json() is another matter: this isn't part of the http module, but of Express itself. Because it's used to send JSON responses, it will set the content type header to application/json (so you don't have to).
But this will only work if the headers haven't yet been sent already: you can't set headers when they have already been sent out. That's why you're getting the error.
If you want to set particular headers in Express, use res.set().
Express evaluates its routes in the order they are added. This means that the route handler passed to .all() will be executed first. In this handler, a response header is written and then next() tells Express to continue iterating its list of routes for another possible matching route.
It then matches the .get() route handler which tries to send a JSON response. However, .json() implicitly sends a response header as well as writes the value passed as JSON to the response and ends the response. This is why you are seeing an error about writeHead() being called more than once.

Handle diff content type in node application

I am developing a api in nodejs which will consume by different application. different application will make call with different content type. I have use the body-parser to parsing req data.
I like to have some middleware to handle the content type and convert data in consistent format so that my controller will work properly.
If if got the call with the 'text/plain;charset=UTF-8' then before calling my controller i have to parse data to json format.
also i have to add some encoding before sending data. in same function i will decode the my data also
please help me to fix this issue.
add this function to server.ts to handle the different response type
app.use(function(req, res, next) {
if (req.headers['content-type'] == "text/plain;charset=UTF-8") {
req.body = JSON.parse(req.body)
}
return next();
});

Why can't we do multiple response.send in Express.js?

3 years ago I could do multiple res.send in express.js.
even write a setTimeout to show up a live output.
response.send('<script class="jsbin" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>');
response.send('<html><body><input id="text_box" /><button>submit</button></body></html>');
var initJs = function() {
$('.button').click(function() {
$.post('/input', { input: $('#text_box').val() }, function() { alert('has send');});
});
}
response.send('<script>' + initJs + '</script>');
Now it will throw:
Error: Can't set headers after they are sent
I know nodejs and express have updated. Why can't do that now? Any other idea?
Found the solution but res.write is not in api reference http://expressjs.com/4x/api.html
Maybe you need: response.write
response.write("foo");
response.write("bar");
//...
response.end()
res.send implicitly calls res.write followed by res.end. If you call res.send multiple times, it will work the first time. However, since the first res.send call ends the response, you cannot add anything to the response.
response.send sends an entire HTTP response to the client, including headers and content, which is why you are unable to call it multiple times. In fact, it even ends the response, so there is no need to call response.end explicitly when using response.send.
It appears to me that you are attempting to use send like a buffer: writing to it with the intention to flush later. This is not how the method works, however; you need to build up your response in code and then make a single send call.
Unfortunately, I cannot speak to why or when this change was made, but I know that it has been like this at least since Express 3.
res.write immediately sends bytes to the client
I just wanted to make this point about res.write clearer.
It does not build up the reply and wait for res.end(). It just sends right away.
This means that the first time you call it, it will send the HTTP reply headers including the status in order to have a meaningful response. So if you want to set a status or custom header, you have to do it before that first call, much like with send().
Note that write() is not what you usually want to do in a simple web application. The browser getting the reply little by little increases the complexity of things, so you will only want to do it it if it is really needed.
Use res.locals to build the reply across middleware
This was my original use case, and res.locals fits well. I can just store data in an Array there, and then on the very last middleware join them up and do a final send to send everything at once, something like:
async (err, req, res, next) => {
res.locals.msg = ['Custom handler']
next(err)
},
async (err, req, res, next) => {
res.locals.msg.push('Custom handler 2')
res.status(500).send(res.locals.msg.join('\n'))
}

Resources