this is the request i want to perform:
POST /v1/oauth2/token HTTP/1.1
Host: api.sandbox.paypal.com
Accept: application/json
Accept-Language: en_US
Authorization: Basic cGF5cGFsaWQ6c2VjcmV0
Content-Type: application/x-www-form-urlencoded
grant_type=client_credentials
I tried it in nodejs using this code:
paypalSignIn = function(){
var username = process.env.PAYPALID;
var password = process.env.PAYPALSECRET;
var auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');
// new Buffer() is deprecated from v6
// auth is: 'Basic VGVzdDoxMjM='
var post_data = querystring.stringify({
'grant_type' : 'client_credentials',
});
var header = {'Accept': 'application/json', 'Authorization': auth, 'Accept-Language': 'en_US'};
const options = {
hostname: 'api.sandbox.paypal.com',
port: 443,
path: '/v1/oauth2/token',
method: 'POST',
headers: header,
}
var post_req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
});
post_req.write(post_data);
post_req.end();
}
Unfortunately i'm getting the following error:
Error: socket hang up
Try using the https module (it's not enough to set port 443, you have to use the HTTPS protocol to connect to an HTTPS endpoint).
I also noticed you didn't set the Content-Type header. It depends on the API, but that may cause problems for you too.
Finally, I'd consider using a library that wraps http/https like node-fetch, bent, or axios for this rather than the standard library directly. It can handle things like writing to the socket, setting the Content-Length header, etc.
Related
I am trying to forward my request from my NodeJS Proxy server to another server. The request I am trying to forward contains FormData()
I created FormData as per MDN docs
const payload = new FormData();
payload.append('addresses', file); // <---- UPLOADED FILE
payload.append('reason', 'reason');
payload.append('type', 'type');
This is how I am essentially sending the request to my NodeJS server
fetch("localhost:3000/v1/addresses", {
method: 'PUT',
body: payload
});
NodeJS Server at localhost:3000
const multer = require('multer');
const upload = multer();
app.put('/v1/addresses', upload.single('addresses'), (req, res) => {
let options = {
host: 'localhost',
method: 'PUT',
port: 8000,
path: req.originalUrl,
headers: req.headers,
formData: {
reason: req.body.reason,
type: req.body.type,
}
};
console.log("reason", req.body.reason) // "reason"
console.log("type", req.body.type) // "type"
console.log("addresses", req.file) // FILE OBJECT
const request = http.request(options, response => {
res.writeHead(response.statusCode, response.headers);
response.pipe(res);
});
request.end();
})
The code above, I'm not sure how to send over the actual file to the other service. Also, I am NOT seeing the reason and and type that I've passed over to the service.
What's also strange is that I see this in the incoming request in my NON- PROXY server
PUT /v1/addresses HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 932
Sec-Ch-Ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"
Sec-Ch-Ua-Mobile: ?0
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryt2p0AWOqJCnz95hg
Accept: */*
Origin: http://localhost:3000
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: http://localhost:3000/blocklist
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
[object Object]
So after lots of searching and experimenting, this post actually provided me with the answer
Here is the code from the post.
const express = require("express");
const app = express();
const bodyParser = require('body-parser');
var multer = require('multer')();
const FormData = require('form-data');
const axios = require('axios');
const fs = require('fs');
app.use(bodyParser.json());
app.post('/fileUpload' , multer.single('fileFieldName'), (req , res) => {
const fileRecievedFromClient = req.file; //File Object sent in 'fileFieldName' field in multipart/form-data
console.log(req.file)
let form = new FormData();
form.append('fileFieldName', fileRecievedFromClient.buffer, fileRecievedFromClient.originalname);
axios.post('http://server2url/fileUploadToServer2', form, {
headers: {
'Content-Type': `multipart/form-data; boundary=${form._boundary}`
}
}).then((responseFromServer2) => {
res.send("SUCCESS")
}).catch((err) => {
res.send("ERROR")
})
})
const server = app.listen(3000, function () {
console.log('Server listening on port 3000');
});
I'm working with a weird HTTP server that only accepts HTTP request which looks like:
GET http://10.0.0.1/test
Host: 10.0.0.1
Cache-Control: no cache
Connection: Keep-Alive
Node the "http://" at the path
When I'm sending HTTP request (using the code at the bottom) the request looks like:
GET /test
Host: 10.0.0.1
Cache-Control: no cache
Connection: Keep-Alive
Code example:
var request = require('request');
var options = {
'method': 'GET',
'uri': 'http://10.0.0.1/test',
'headers': {
'Host': '10.0.0,1',
'Cache-Control': 'no cache',
'Connection': 'Keep-Alive'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Any idea how I can send the request like the server expects using standard libaries?
I'm using node.js default HTTP module and have an HTTP webserver.
I use request.headers to get all headers, but when I try to do request.headers.authorization it returns undefined, but there IS authorization as you can see here.
I tried to do JSON.parse(request.headers).authorization, still undefined, and crashes the process. How can I get the authorization header content?
Maybe you could use the method request.getHeader(name)
I looked in https://nodejs.org/api/http.html#http_request_getheader_name
Edit 1:
index.js
const http = require('http');
const server = http.createServer((request, response) => {
console.log(request.headers);
console.log(request.headers.authorization);
console.log('----');
const headers = {
'Content-Type': 'text/plain',
};
let statusCode = 404;
response.writeHead(200, headers);
response.end('Hi');
});
server.listen(8080, () => {
console.log(`Server listening on port :8080 🚀`);
});
Executing in terminal one:
node index.js
Terminal two:
curl localhost:8080 -H 'authorization: hello'
The output in terminal one is:
{ host: 'localhost:8080',
'user-agent': 'curl/7.68.0',
accept: '*/*',
authorization: 'hello' }
hello
----
currently i am working on my services to send TLS certificates with each soap services, i have created the client and server side which accepts soap request with certificate(JKS) in java... But i am not able to find any examples that client side nodejs to send soap request with JKS or PEM files.
Could you please help me on this, if you have any link where i can get information about nodejs example to send soap request to server with TLS certificates.
Thanks in advance.
For the self-signed certificate pinning. I only find out a way to do that one by https module. For example below:
const fs = require('fs');
const https = require('https');
const options = {
hostname: 'localhost',
port: 8080,
path: '/',
method: 'POST',
ca: fs.readFileSync('ca-crt.pem')
};
const req = https.request(options, function(res) {
res.on('data', function(data) {
process.stdout.write(data);
});
});
req.end();
!Noted: when you send to soap you have to check carefully the header and body like.
+ 'cache-control': 'no-cache',
+ 'soapaction': actionName,
+ 'content-type': 'text/xml;charset=UTF-8',
I am trying to make a simple request using http.get. But I need to make this request through Squid proxy. Here's my code:
var http = require('http');
var username = 'username';
var password = 'password';
var host = "proxy_host";
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
var options = {
host: host,
port: 3128,
path: "http://www.google.com",
authorization: auth,
headers: {
Host: 'www.google.com'
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
});
req.end();
My username and password is correct according to the ops team that set up the proxy. The problem is that I keep getting a 407 - authorization required status coming back.
Is there something wrong with the way I am making the request? Or does Squid proxy need to be configured?
Thanks in advance.
You should include auth in the headers section of options:
var options = {
host: host,
port: 3128,
path: "http://www.google.com",
headers: {
'Proxy-Authorization': auth,
Host: 'www.google.com'
}
};