am a fresher working on nodejs.
1. My friend is working on reactjs,he designed a UI where he can perform RESTFULL API methods.He would send his request to me to access API's.
2. Am working on Nodejs,i will take his request and send it to "Leadsquared.com" website which has APIs, once i receive the response from website,then i will have to forward the response to my friend back again.
Note: Am not using database, but just take request then send to website and receive response, send it back to my friend.
Need your suggestions and help!!
You need to use the http.request method.
like this:
var options = {
host: "your url",
path: '/yourPath?id=someId',
method: 'POST'
};
http.request(options, function(res) {
res.on('data', function (chunk) {
//do something
});
}).end();
Related
Not sure if this is possible but Id like to run a test without invoking an external API POST request.
Whats currently happening is ive got a test confirming the post data sent to my server API is processed correctly, as it needs to add some basic additional information to the BODY before sending it to the external API, and then the server makes another POST request to an external API with this modified BODY.
This is all done in the below function.
createUser(req,res){
...
// schema validation,
// adding fields
// external server post request
}
Is it possible to have my test ignore the external API call?
the test looks like
it('POST users --> 200 Successful Post', () => {
return request(app).post('/api/users').send(........ my json .......)
.expect('Content-Type', /json/)
.expect(200)
.then((response) => {
expect(response.body).toEqual(
......
)
})
});
You can use nock to intercept and mock requests for testings.
On your test, you can setup your mocking object like this:
const nock = require("nock");
const scope = nock("https://api.github.com")
.get("/repos/atom/atom/license")
.reply(200);
It will intercept an HTTPS GET requests to /repos/atom/atom/license.
How to Test Node.js Apps That Interact With External APIs
What is the difference between the request in this line of code:
http.createServer(function(request,response){. . .}
and request in
http.request()
Are both requests done to the server?
I am new to node.js and I am sorry if I sound dumb!
How does http.request() work?
In http.request() we fetch data from another site but in order to fetch data from another site we first need to go to our site and then make a request? Explain it with a simple real-life example!
http.request() makes a request to another HTTP server. Suppose for some reason I wanted to go download Stack Overflow's home page...
http.request('https://stackoverflow.com/', (res) => {
// ...
});
http.createServer()... it creates an HTTP server. That is, it binds your application to a socket to listen on. When a new connection is made from somewhere or something else, it handles the underlying HTTP protocol of that request and asks your application to deal with it by way of a callback. From the Node.js documentation:
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('okay');
});
These two methods have absolutely nothing to do with each other. http.request() is for making a request to an HTTP server. http.createServer() is for creating your own HTTP server. Don't get confused by the callbacks.
Based on the source code of nodejs (extract below), createServer is just a helper method to instantiate a Server.
Extract from line 1674 of http.js.
exports.Server = Server;
exports.createServer = function(requestListener) {
return new Server(requestListener);
};
The http.request() API is for when you want your server code to act as a client and request content from another site and has GET, POST, PUT, DELETE methods.
Say I have the following code that sends back json data (that I get from example.com first) back to a user that made a post request
app.post('/riot', function(request, response) {
var riotAPI = https.get("https://example.com", function(riotResponse){
var body = "";
riotResponse.on('data', function(chunk){
body+= chunk;
});
riotResponse.on('end', function(){
response.type('json');
response.end(body);
});
});
});
What do I do if I want to get more data from a different website and send json data from both website back to user? I am using express.
There are a number of ways you can do this. I would suggest using the request npm module instead of calling https directly. With request you can simply pass in callback which is called when a request finishes, so no need to deal with chunks of data.
If you take this approach then you can just use something like async.parallel() to run both requests in parallel. async.parallel takes one callback that is called when all of its async functions have finished.. and that is where you would send your response.
I have made a couchdb design document which works perfectly on the following url
http://localhost:5984/db/_design/app/index.html
Now the problem is i am trying to fetch the page contents and display it from node js but only the html page is displayed the linked css and js files are not working and when i tried to narrow down the problem i found that the css and js files are suppose to have the login credentials of the couchdb and is not linking I even tried adding the auth header in the response parameter but still no luck
var http = require('http');
var json;
var root = new Buffer("admin:pass").toString('base64');
http.createServer(function(req, res) {
res.setHeader('Authorization', root);
res.writeHead(200, { 'Content-Type':'text/html' });
couchPage();
res.end(json);
}).listen(8080);
function couchPage() {
var options = {
hostname: 'localhost',
port: 5984,
path: '/db/_design/app/index.html',
auth: 'admin:pass',
method: 'GET'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
json = chunk;
});
});
req.end();
}
could any one please guide me where am i wrong
I think this has nothing to do with couchdb authorization. The problem is that you do not perform any routing on your nodejs server. That is, the browser makes a request to localhost:8080 and receives the content of /db/_design/app/index.html as an answer. Now, the browser detects a link to a stylesheet, say "style.css". It performs a request to localhost:8080/style.css but your nodejs server simply ignores the "style.css" part of the request. Instead, the client will receive the content of /db/_design/app/index.html again!
If you want to serve attachments of your design document through nodejs, you have to parse the request first and then retrieve the corresponding document from couchdb. However, I don't think that you actually want to do this. Either you want to use couchdb in a traditional way behind nodejs (not directly accessible from the client) and then you would just use it as a database with your html (or template) files stored on disk. Or you want to directly expose couchdb to the client and make nodejs listen to events via the couchdb _changes feed.
I have created a rest client to make calls outside of my application. I want to send the data I receive back from the rest calls to the client's web browser.
Something like the following, but what is the best way to structure the code to allow access to the response to write back to the web browser with as loose coupling as possible? I don't want to define the rest client within a request handler.
var servReq = http.request(options, function(restResponse){
var status = restResponse.statusCode
var headers = restResponse.headers
restResponse.setEncoding("utf8");
d='';
restResponse.on('data', function(chunk){
d += chunk;
})
restResponse.on('end', function(restResponse){
// res would be a response to write back to the client's web browser
// with the data received from the rest client.
res.writeHead(200, {"content-type":"text/plain"})
res.write(d)
res.end();
})
}
Using request, you can pipe the API response straight to your application's response. This way it'll be completely loosely coupled—your server will return precisely what the API returns.
request(options).pipe(res);
https://github.com/mikeal/request#streaming