POSTing JSON w/ node.js - javascript

I have two node.js files: "client" and "server". "Server" just listens for any http requests, and then writes the request object to console when it is received. This works as expected for GET requests. When I write a client like the one below that POSTs JSON, it seems to work fine except there is no JSON anywhere in the request that is output to console on "Server".
In the output that "server" prints to console, all the other request specific things are there, such as host: '127.0.0.1', url: '/some/path', method: 'POST'
But no reference to any of the JSON that was POSTed....items like username:'someUser',email:'some#email.com',firstName: 'SomeFN',lastName: 'SomeLN'
complete console output from "Server" is here.
//client
var http = require('http');
var user = {
username: 'someUser',
email: 'some#email.com',
firstName: 'SomeFN',
lastName: 'SomeLN'
};
var userString = JSON.stringify(user);
var headers = {
'Content-Type': 'application/json',
'Content-Length': userString.length
};
var options = {
host: '127.0.0.1',
port: 80,
path: '/some/path',
method: 'POST',
headers: headers
};
// Setup the request. The options parameter is
// the object we defined above.
var req = http.request(options, function(res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
var resultObject = JSON.parse(responseString);
});
});
req.on('error', function(e) {
// TODO: handle error.
});
req.write(userString);
req.end();
.
//server
var http = require('http');
var stringify = require('json-stringify-safe');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(stringify(req, null, 2));
console.log(req)
}).listen(80, '127.0.0.1');

Related

Implementing CoAP protocol on node.js

Do you know any guides or tutorials about implementing CoAP protocol connection on node.js? I have to implement simple server and client application. I've checked all the resources I've found, including of course their documentation:
https://github.com/mcollina/node-coap
but it is still unclear for me.
Thank you for any help.
EDIT:
If this is implementation of server, how should look client like?
var coap = require('coap')
, server = coap.createServer()
server.on('request', function(req, res) {
res.end('Hello ' + req.url.split('/')[1] + '\n')
})
// the default CoAP port is 5683
server.listen(function() {
var req = coap.request('coap://localhost/Matteo')
req.on('response', function(res) {
res.pipe(process.stdout)
res.on('end', function() {
process.exit(0)
})
})
req.end()
})
or like this , an example for coap client
const coap = require('coap'),
bl = require('bl');
//construct coap request
var req = coap.request({
observe: false,
host: '192.168.0.93',
pathname: '/',
port: 5683,
method: 'get',
confirmable: 'true',
retrySend: 'true',
//query:'',
options: {
// "Content-Format": 'application/json'
}
})
//put payload into request
var payload = {
username: 'aniu',
}
req.write(JSON.stringify(payload));
//waiting for coap server send con response
req.on('response', function(res) {
//print response code, headers,options,method
console.log('response code', res.code);
if (res.code !== '2.05') return process.exit(1);
//get response/payload from coap server, server sends json format
res.pipe(bl(function(err, data) {
//parse data into string
var json = JSON.parse(data);
console.log("string:", json);
// JSON.stringify(json));
}))
});
req.end();
It should be like this:
const coap = require('coap')
req = coap.request('coap://localhost')
console.log("Client Request...")
req.on('response' , function(res){
res.pipe(process.stdout)
})
req.end()
Source: https://github.com/mcollina/node-coap/blob/master/examples/client.js

POST method through node.js

I am writing a simple node.js for a REST API call to create object through POST method and get the response code. But while running the script I get "0 passing" .
Here is my code:
var request = require("request");
var options = { method: 'POST',
url: 'https://example.org',
headers:
{ 'content-type': 'application/vnd.nativ.mio.v1+json',
authorization: 'Basic hashedTokenHere' },
//body: '{\n\n"name": "My JS TEST",\n"type": "media-asset"\n\n}'
};
request(options, function (error, response, body) {
if(error) {
console.log(error);
} else {
console.log(response.statusCode, body);
}
});
Can anyone help to to run it successfully and get the response code?
Thanks!
I calling my local API hope this will make thing get clear. It's work for me
This my API
var express = require('express')
var router = express.Router()
var bodyParser = require('body-parser');
var app=express()
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/api',function(req,res)
{
res.status(200).send(req.body.name+"hi");
})
app.listen(8080,function(){
console.log("start");
})
Now, through Request, i will request this post method
var request = require('request');
// Set the headers
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-type': 'application/json',
'Authorization': 'Basic ' + auth,
}
var postData = {
name: 'test',
value: 'test'
}
// Configure the request
var options = {
url: 'http://127.0.0.1:8080/api',
method: 'POST',
json: true,
headers: headers,
body: postData
}
// Start the request
request(options, function (error, response, body) {
// Print out the response body and head
console.log("body = "+body+" head= "+response.statusCode)
}
})

How to extract data from XML using node.js

how to extract data from XML type rest API using node.js?
This is the code i used to get data by sending rest api request:
//Load the request module
var request = require('request');
//Lets configure and request
request(
{
url: 'http://nemo.sonarqube.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverage', //URL to hit
method: 'GET', //Specify the method
headers: { //We can define headers too
'Authorization': 'Basic ' + new Buffer( 'admin' + ':'+'admin').toString('base64'),
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
},
function(error, response, body){
if(error) {
console.log(error);
} else {
var obj=JSON.parse(response.body);
console.log(obj.id);
}
}
)
var express = require('express');
var app = express();
var server = app.listen(3000,function (){
console.log('port 3000');
}
);
When I send the request using a browser, the result appears like:
<resources>
<resource>
<id>400009</id>
<key>DEV:Fabrice Bellingard:org.codehaus.sonar:sonar</key>
<name>SonarQube</name>
<lname>SonarQube</lname>
<scope>PRJ</scope>
<qualifier>DEV_PRJ</qualifier>
<date>2015-08-04T13:10:57+0000</date>
<creationDate/>
<copy>48569</copy>
<msr>
<key>ncloc</key>
<val>879.0</val>
<frmt_val>879</frmt_val>
</msr>
<msr>
<key>coverage</key>
<val>81.8</val>
<frmt_val>81.8%</frmt_val>
</msr>
</resource>
</resources>
I want to extract the id and print it on the console using node.js.
How I want to edit the above code?
The problem is response.body is in array format, so get the first item in the array and then its id value
//Load the request module
var request = require('request');
//Lets configure and request
request({
url: 'http://nemo.sonarqube.org/api/resources?resource=DEV:Fabrice%20Bellingard:org.codehaus.sonar:sonar&metrics=ncloc,coverage', //URL to hit
method: 'GET', //Specify the method
headers: { //We can define headers too
'Authorization': 'Basic ' + new Buffer('admin' + ':' + 'admin').toString('base64'),
'Content-Type': 'MyContentType',
'Custom-Header': 'Custom Value'
}
}, function (error, response, body) {
if (error) {
console.log(error);
} else {
var arr = JSON.parse(response.body);
var obj = arr[0];
console.log(obj.id);
}
})
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
console.log('port 3000');;
});

How to send form data in node.js

I am able to get to the server but unable to post my form data.
How should I post the form data with the https request?
I am using form-data library for form-data, and https request for post call.
When I run the following code, I am able to reach the service, but the service gives a response saying that the form data is not submitted.
var https = require('https');
var FormData = require('form-data');
//var querystring = require('querystring');
var fs = require('fs');
var form = new FormData();
connect();
function connect() {
username = "wr";
password = "45!"
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
var options = {
hostname: 'trans/sun.com',
port: 443,
path: '/transfer/upload-v1/file',
method: 'POST',
rejectUnauthorized: false,
headers: {
'Authorization': auth,
'Content-Type': 'application/json',
//'Content-Length': postData.length
}
};
form.append('deviceId', '2612');
form.append('compressionType', 'Z');
form.append('file', fs.createReadStream('/Mybugs.txt'));
var req = https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
//console.log("headers: ", res.headers);
res.setEncoding('utf8');
res.on('data', function(d) {
console.log(d)
});
});
req.write(form + '');
req.end();
req.on('error', function(e) {
console.error(e);
});
}
You never link your form to your request. Check this example provided with the form-data documentation
var http = require('http');
var request = http.request({
method: 'post',
host: 'example.org',
path: '/upload',
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function(res) {
console.log(res.statusCode);
});

nodejs http post request throws TypeError

I am trying to make a simple server that use google oauth (without express and passportjs, as I want to study the data exchanged).
When my program attempts to send a post request to google, nodejs throws:
http.js:593 throw new TypeError('first argument must be a string or Buffer');
I have checked and make sure that all parameters in query and option are all string, but the error still persist. What could I have missed here?
Here is my code:
// Load the http module to create an http server.
var http = require('http');
var url = require('url');
var fs = require('fs');
var querystring = require('querystring');
var content;
fs.readFile('./test.html',function(err,data){
content = data;
});
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
var path = url.parse(request.url).pathname;
var query = querystring.parse(url.parse(request.url).query);
var code;
if (query!=null) {
code = query.code;
};
if ('/auth/google/callback'==path){
var data = querystring.stringify({
'code': ''+code,
'client_id': 'id',
'client_secret': 'secret',
'redirect_uri': 'http://localhost:8999/auth/google/code/callback',
'grant_type': 'authorization_code'
});
var options = {
hostname: 'accounts.google.com',
port:'80',
path: '/o/oauth2/token',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': ''+data.length
}
};
debugger;
var post = http.request(options, function(res){
response.write(res);
response.end();
});
debugger;
post.write(data);
debugger;
post.end();
}
else if (path=='/auth/google/code/callback'){
console.log(request.headers);
console.log(request.url);
}
else response.end(content);
console.log(request.headers);
console.log(request.url);
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8999);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
Many thanks,
I think problem is when you are saying
response.write(res); //it needs a string
I think res is an object here.
try
response.write(JSON.stringify(res));
When you write response or request. It should contain string so you need to change it to
response.write(querystring.stringify(res));
or
response.write(JSON.stringify(res));

Categories