Sending data to app.delete in node.js - javascript

I am trying to delete a certain input from my database. I cant seem to get the data to come through on an app.delete to know which entry to delete. However app.post gets the data. Here is my code
Client:
let userToDelete = {
data:entryToDelete
}
httpRequest.delete(url, userToDelete)
.then(function (response) {
//...
Server
app.delete('/api/deleteEntry', function(req, res){
console.log('going to delete', req.body);
//...
});
now if I change to httpRequest.post and app.post, req.body console logs the data I send. Does a .delete request not get the data?

RFC2616 says:
The DELETE method requests that the origin server delete the resource
identified by the Request-URI.
Request bodies are not explicitly disallowed for HTTP DELETE requests, but I wouldn't rely on them always being available. You'll have to include some sort of ID or primary key in your request URI, so that your server can pass that along to your database for deletion.

Related

Send body JSON with Postman in a POST method to execute procedure in ms sql server

I want to send a JSON (body) on Postman with POST method and receive a result.
Im a trainee and my boss asked me this. I've been looking in web for a week and didn't find. I said to him that method to receive a data is GET, but he said that GET has a limit on URL. If the stored procedure have a lot of parameters we will not receive the expected result, so a I have to use Post method.
This is my code to connect to ms sql server:
var express = require('express');
var app = express();
var sql = require('mssql');
var config = {
user: 'MY_USER',
password: 'MY_PASS',
server: 'MY_SERVER',
database: 'MY_DB'
};
Searching in google I found a way to execute a procedure with GET method. In the browser I put the value I want and I receive the result, but is not still what he wants. The code is:
app.get('/get/:pNU_EST001', function (req, res) {
//conexão com o DB
sql.connect(config, function(){
var request = new sql.Request();
request.input('pNU_EST001', req.params.pNU_EST001);
request.execute('dbo.ESTSP004_ConsultaLivrosEmprestadosAluno_XX', function(err, recordsets, returnValue, affected) {
if(err) console.log(err);
res.send(recordsets);
//res.end(JSON.stringify(recordsets)); /*--- result in JSON format ---*/
});
});
});
On Postman he showed me a example with DB2, but I couldn't see the code. On Post Method, on HEADERS it has two key:
KEY => Content-Type (value: application/json) // KEY => Accept (value: application/json)
And in his example, on BODY, he wrote a JSON like: { "pNU_EST001" : "3"} and received the related result below. That's what I need.
Express has a few other verbs to use you are using
app.get but there is also app.post if you change your code to use the latter instead it will handle a post request
app.post('/path', function (req, res) {
Then in express to get values from the POST body you get that from
req.body property
So in your case you would want to use req.body.pNU_EST001 instead of req.params.pNU_EST001

Handling ajax requests, not receiving data

i'm having a hard time setting up my client-side ajax calls to send data to node express server.
i want to fire my ajax request "onclick" of an href link.
I'm trying to send the ID of the link as a variable to the server, but the server doesn't receive my data (without setInterval)
if i put the ajax request inside a setInterval() (which i don't want to do, because i only want to send the data once a link is clicked to the server),
the server receives the data in res.req.body, why?
client side:
$('.link_group').click(function () {
data = $(this).attr('id');
$.ajax({
type: "POST",
url: "/ajax_handler",
data: {id: data}
});
});
server side
app.post("/ajax_handler", function(req, res) {
res.send({ //works as it should....
user : req.session.user,
data_objekt: req.session.data
});
if(res.req.body) {
console.log(res.req.body);
}
});
Is this even a common way to "catch" the data from client?
if(res.req.body) {...
doesn't seems right, but i don't know how to do it in a smarter way / can't find any good examples.
I'm about to fire 3-4 Ajax other requests to /ajax_handler which leads to my next question: how to handle multiple ajax requests to the same url?
Thanks in advance!
Are you parsing the request? req.body is initially empty/undefined. You will need to pass it to a middleware that parses the data into req.body. Body-parser is a nodejs module that can achieve this. Here's how to a POST request with JSON data being sent.
const bodyParser = require('body-parser')
app.use(bodyParser.json());
app.post("/ajax_handler", function(req, res) {
res.send({ //works as it should....
user : req.session.user,
data_objekt: req.session.data
});
if(req.body) {
console.log(req.body);
}
});

How to perform a POST request with session data to an endpoint within the server node js

I am working on express and I need to perform a POST request to an endpoint within the server. My code for this is :
request({
url : 'http://localhost:3000/api/oauth2/authorize',
qs:{
transaction_id:req.oauth2.transactionID,
user:req.user,
client : req.oauth2.client
},
headers:{
'Authorization':auth,
'Content-Type':'application/x-www-form-urlencoded'
},
method:'POST'
},function(err,res,bo){
console.log("Got response with body :"+bo);
});
localhost is the current server, this works properly but the session data is lost when i perform the POST request.
Is there any other way to perform a POST within the same server or to save the session data such that it is maintained after the POST?
Well, typically you register your routes something like:
var handlePostRequest = function(req,res,next) {
// process req.body etc.
};
app.post('/api/oauth2/authorize', handlePostRequest);
If you want to call that endpoint from within your application, you simply call handlePostRequest() providing the req, res, next objects as well.
Assuming handlePostRequest is in global scope, or required already; in your example that would be:
app.get('/some/other/endpoint', function(req,res,next){
// override the default req.body with your supplied data
req.body = {
transaction_id: req.oauth2.transactionID,
user: req.user,
client: req.oauth2.client
};
// you may also override req.headers etc. for authorization
// ...
// then call the "api" again with the new values
return handlePostRequest(req,res,next);
});
IF you however strictly want to make a POST request (for some reason), you need to supply the sessionID as well, which will be in your cookie. Then the session data will be available.

How to run one request from another using Pre-request Script in Postman

I'm trying to send an authenticated request with one click in postman.
So, I have request named "Oauth" and I'm using Tests to store the token in a local variable.
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", jsonData.access_token);
What I'm trying to do now is that run the Oauth request automatically (from a pre-request script) for any other requests which needs a bearer token.
Is there a way to get an access token and send an authenticated request with one postman button click?
As mentioned by KBusc and inspired from those examples you can achieve your goal by setting a pre-request script like the following:
pm.sendRequest({
url: pm.environment.get("token_url"),
method: 'GET',
header: {
'Authorization': 'Basic xxxxxxxxxx==',
}
}, function (err, res) {
pm.environment.set("access_token", res.json().token);
});
Then you just reference {{access_token}} as any other environment variable.
NOTE: There now is a way to do this in a pre-request script, see the other answers. I'll keep this answer for posterity but just so everyone knows :)
I don't think there's a way to do this in the pre-request script just yet, but you can get it down to just a few clicks if you use a variable and the Tests tab. There are fuller instructions on the Postman blog, but the gist of it is:
Set up your authentication request like normal.
In the Tests section of that request, store the result of that request in a variable, possibly something like the following:
var data = JSON.parse(responseBody);
postman.setEnvironmentVariable("token", data.token);
Run the authentication request -- you should now see that token is set for that environment (click on the eye-shaped icon in the top right).
Set up your data request to use {{token}} wherever you had previously been pasting in the bearer token.
Run your data request -- it should now be properly authenticated.
To refresh the token, all you should need to do is re-run the authentication request.
You can't send another request from Pre-request Script section, but in fact, it's possible to chain request and run one after another.
You collect your request into collection and run it with Collection Runner.
To view request results you can follow other answer.
The same question was on my mind, which is basically "how can I run another request that already exists from another request's test or pre-request script tabs without building that request with pm.sendRequest(reqConfObj)?", then I found the postman.setNextRequest('requestName') method from this Postman discussion which is gonna lead you to this postman documentation page about building request workflows.
But the thing is, postman.setNextRequest() method will not run if you are not running a folder or a collection, so simply hitting the 'Send' button of the request that has your script won't work.
I also would like to draw your attention towards some things:
The prepended word, it's 'postman' instead of 'pm'.
postman.setNextRequest() will always run last, even though you have written it to the top of your script. Your other code in the script will be ran and then postman.setNextRequest will initialize.
If you would like to stop the request flow, you could simply postman.setNextRequest(null).
I would encourage everyone that uses Postman to check out the links that was mentioned, I believe it's a great feature that everybody should give it a try! :)
All these workarounds with recreating requests. Postman does not support what you want to do. In order to get what you want, you have to use Insomnia, it allows you to map body values from other request responses and if those responses are not executed ever it automatically runs them or behaves based on chosen policy.
But if you want to stick with Postman, then you'll have to save full previous request params to global variables, then retrieve all configuration of previous requests from that variable as a JSON string, parse that JSON into an object and assign it to pm.sendRequest as the first argument.
You can add a pre-request script to the collection which will execute prior to each Postman request. For example, I use the following to return an access token from Apigee
const echoPostRequest = {
url: client_credentials_url,
method: 'POST',
header: 'Authorization: Basic *Basic Authentication string*'
};
var getToken = true;
if (!pm.environment.get('token')) {
console.log('Token missing')
} else {
console.log('Token all good');
}
if (getToken === true) {
pm.sendRequest(echoPostRequest, function(err, res) {
console.log(err ? err : res.json());
if (err === null) {
console.log('Saving the token');
console.log(res);
var responseJson = res.json();
console.log(responseJson.access_token);
pm.environment.set('token', responseJson.access_token)
}
});
}
First, add pre-request script:
pm.sendRequest({
url: 'http://YOUR_SITE',
method: 'POST',
body: {
mode: 'urlencoded',
urlencoded: [
{ key: "login", value: "YOUR_LOGIN" },
{ key: "password", value: "YOUR_PASSWORD" }
]
}
}, function (err, res) {
if (err === null) {
pm.globals.set("token", res.json()["access_token"]);
}
});
Second, set custom variable(after you can use it value):
Third, you can use variable by {{VARIABLENAME}}, for example:
If you are setting token in your auth token you can copy its request configuration to env once (in test script section) and automatically call it from other request and use token from env.
It originally mentuioned here: https://community.postman.com/t/use-existing-postman-request-in-pre-post-script/23477/5
Copy current request config to env in auth test script:
let r=pm.response.json();
pm.environment.set("access_token", r.access_token);
pm.environment.set("refresh_token", r.refresh_token);
pm.environment.set("auth_req", pm.request);
And then call it on other endpoints:
pm.sendRequest(pm.environment.get("auth_req"))
I have tried multiple solutions, the below solution is related to when you are parsing the response for request 1 and passing any variable into the second request parameter. ( In this Example variable is Lastname. )
Note:- data and user are JSON objects.``
postman.clearGlobalVariable("variable_key");
postman.clearEnvironmentVariable("variable_key");
tests["Body matches string"] = responseBody.has("enter the match string ");
var jsonData = JSON.parse(responseBody);
var result = jsonData.data;
var lastName = result.user.lastName;
tests["Body matches lastName "] = responseBody.has(lastName);
tests["print matches lastName " + lastName ] = lastName;
You can use a function sendRequest of postman.
Some examples here.
https://gist.github.com/sid405/b57985b0649d3407a7aa9de1bd327990

Unexpected End of Input - curl JSON on Express/Node App

I have an Express/Node app that is deployed to a Heroku instance. The app has a POST api endpoint that expects a .json file, reads the data, and populates the app with the JSON data. Below is the backend code that handles the POST request:
router.route('/data')
.post(function (req, res) {
return DataUtils.storeData(req, res);
});
Utils.storeData = function (req, res) {
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
file.on('data', function(data) {
var data;
try {
data = JSON.parse('' + data); // quick casting into a String
var numPersonSessionObj = data.length;
...
// etc etc...
When we try to make the request via the curl command below:
curl -H "Content-Length: 5567" -F file=#sample_data/sample_json.json
http://[heroku-instance]/api/data
The server sometimes works fine, and uploads the data, and other times, throws an "Unexpected end of input" error. It seems as though the buffer method we're using is not reading all of the data for some reason. Upon logging the data.length in the code above (i.e. the JSON), it seems as though the request fails whenever the data length is less than its supposed to be. Is there something wrong with how I'm reading in the JSON file above? Thanks--
The data event only indicates that some data was received – not that all data was received. You want to wait for the end event before parsing your JSON. See this example from the official documentation for further details: https://nodejs.org/api/stream.html#stream_api_for_stream_consumers
Content-Length must be the count of octets the response body.
if you try using the value of
data.length
rather than
Buffer.byteLength(data)

Categories

Resources