I am writing a node application using express JS. Usually in this application we consumes res apis and merge them in one object and send it to angular application.
As a rest client I am using superagent. One of my colleague has written reverse proxy code using http-proxy-middleware.
Using superagent I make a call like below and it does not use http-proxy-middleware as i have mentioned in code.
let request = require("superagent");
request.get("applications-api/1/anotherendpoint")
.set("Content-Type", "application/json")
.set("x-application", applicationId)
.then((response) => {
res.send(response.body);
})
.catch((err) => {
res.json(err)
});
Usually http call should go through middleware since we have that middleware used in express server like but it does not do. In middleware we are using actual endpoint when path matches to "^applications-api", but its not happening. Superagent expecting url which starts from http://endpoint.com/1/anotherendpoint but I want it to be used from proxy-middleware.
Is there anything to do with superagent configuration in order to use http-proxy-middleware ?
Kindly suggest. Any help would be greatly appreciated.
Thanks
Related
Currently, I am developing a simple project, which uses strong-soap module and expressjs. To create a soap server, I have to use http module of NodeJs, using express for soap module causes errors (wsdl file content can't be seen in browser). And i declare my routes and its functions by help of ExpressJS. My simple codebase is similar to the given below.
index.js
const app = require('express')();
const http = require('http');
var MyServiceObject = { /* ...some methods which exist in wsdl file */ };
var xml = require('fs').readFileSync('myWsdlFile.wsdl');
let server = http.createServer(function(request,response) {
response.end("404: Not Found: " + request.url);
});
server.listen(8000);
soap.listen(server, '/wsdl', MyServiceObject, xml);
/*########################### SOME ROUTES ############################################*/
app.listen(8002, (req, res) => {
console.log('App is listening on port 8002');
});
I am concerning about security, so i have a long question:
I'm not able to apply some authorization processes on HTTP Object in my code. How i can apply authorization on http? Is leaving http object as seen in code block, causes some security problems? Must i apply some authorization processes on http object? And i am using strong-soap server in this project. Must i apply some authorization processes on strong-soap object also. I can apply authorization processes on Express.js. Is applying authorization processes on express object (app) is sufficient for security?
Thanks in advance.
You can go with the soap package (https://www.npmjs.com/package/soap), you will get more flexibility to work with. Also, you can install the soap client (https://www.soapui.org/downloads/soapui/) to test services before implementing them with Node.js. It will help you to understand the request and response of each service.
We use axios for http requests such as get, post, etc.
We use express for the same purpose also.
However according to what I read, they are for different purposes.
Please explain how.
PS: If you explain it by giving an example, it would be great!
You can think of express.js as a warehouse:
app.get('/item/:name', async function (req, res) {
res.send(await findItemByName(req.params.name));
});
If you want to get an item, for example a pencil, from this warehouse, you can use axios.js.
axios.get('/item/pencil')
Axios is used to send a web request whereas express is used to listen and serve these web requests.
In simple words, express is used to respond to the web requests sent by axios.
If you know about the fetch() method in javascript, axios is just an alternative to fetch().
I would say that express is used to create HTTP servers. So the server runs somewhere and responds to a request.
Axios is an HTTP client. It creates requests!
In very simple words axios is just passing the web request to the server-side (express). They basically work together (axios -> express -> DB)
I want my java REST api make a call to a Node js rest service. I want to pass an object that contain string messages which can be parsed and used inside the Node Js's methods and the result is returned to my java REST Service. I need demo code please.
Simply NPM install --save express Axios
then in your app.js file add this code:
change http://localhost:port/users to your java API endpoint.
Your request should now work fine and you should see the data.
const express = require("express");
const axios = require("axios");
const router = express.Router();
console.log("'/test' call");
axios.get("http://localhost:port/users")
.then(data => res.json(data))
.catch(err => res.secn(err));
You can use any http client api to make such a request, my recommendation is axios, while there are many apis like fetch etc.
I'm using express as backend. I implemented facebook authentication at the backend.
router.get('/login/facebook',
passport.authenticate('facebook',{scope:['email']}));
router.get('/login/facebook/callback',
passport.authenticate('facebook',{
successRedirect : '/home',
failureRedirect:'/'
})
);
Now I want to call this through my react app, so that when the user lands up at home page, first he should be authenticated by facebook then only he can see homepage. How can I do this ?
I tried using react-router, but I can't understand how to call backend using react-router.
I also fetched /login/facebook using fetch command :
componentDidMount(){
fetch("127.0.0.1:3001/login/facebook");
But it gave me CORS error.
My react app is at 127.0.0.1:3000 and express server at 127.0.0.1:3001.
If this issue is only in dev mode, then Daniel's answer is correct.
In any case, I recommend to avoid calling the :3001 api directly from the :3000 app. Here's what I would do.
I will edit the fetch call as follows,
componentDidMount(){
fetch("/login/facebook");
}
This call will be received by the backend which serves the react application.
Now there are three cases,
Case 1: Your file serving app will have a proxy method which can forward requests to an API. For example read it here
Case 2 This is my Recommended approach. I would simply write the authentication logic in the :3000 server and only use the :3001 API for handling business logic of the app.
Case 3: If you have a backend app (:3000), say written using expressJs, you can forward the request to the :3001 API. Here is a sample code for that,
client.send({
method: req.method,
path: req.url,
data: req.body,
params: req.params
}).then( (response) => {
// Something
}).catch( (err) => {
// Handle error
});
Here the client is a module which uses the request module to make HTTP calls.
You can implement the above call as an express middleware to use it for all HTTP calls.
There are several options:
If you are using webpack dev server, you can set up a proxy to your api. See here
You can temporary disable cors validation during development. See here
I did a Node.js meetup presentation and was unable to answer this question. It is still bothering me.
Suppose I have a legacy http application or an Express.js application. It is a function, of the form
function legacy_app(request, response) {
// Handle the request.
}
Suppose I adopt Hapi.js for new versions of my application. But I have lots of debugged legacy or upstream code which I wish to integrate into the Hapi application. For example, a legacy vhost will run the legacy version, or it is accessible inside a /legacy namespace in the URL.
What is the best way to do this?
Wrapping existing HTTP node server dispatch function for use as a hapi handler is probably ok but you must add to your hapi_wrap function (at the end):
reply.close(false);
so that hapi can finish handling the request without messing with you legacy logic (https://github.com/spumko/hapi/blob/master/docs/Reference.md#replycloseoptions).
Wrapping Express handler/middleware is much more complicated because you are probably relying on some other middleware (e.g. body parser, cookie parse, session, etc.) and using some of the Express decorator that are not part of node (e.g. res.send(), res.json(), etc.).
The only way I can think to do this is manually. Just directly break the advice in the documentation: pull out the raw request and response objects and pass them to the legacy handler.
// An application built with http core.
var http = require('http')
var legacy_server = http.createServer(legacy_handler)
function legacy_handler(request, response) {
response.end('I am a standard handler\n')
}
// An express application.
var express = require('express')
var express_app = express()
express_app.get('*', function(request, response) {
response.send('I am an Express app\n')
})
// A Hapi application.
var Hapi = require('hapi')
var server = new Hapi.Server(8080, "0.0.0.0")
server.route({path:'/', method:'*', handler:hapi_handler})
function hapi_handler(request, reply) {
reply('I am a Hapi handler\n')
}
// Okay, great. Now suppose I want to hook the legacy application into the
// newer Hapi application, for example under a vhost or a /deprecated namespace.
server.route({path:'/legacy', method:'*', handler:hapi_wrap(legacy_handler)})
server.route({path:'/express', method:'*', handler:hapi_wrap(express_app)})
// Convert a legacy http handler into a Hapi handler.
function hapi_wrap(handler) {
return hapi_handler
function hapi_handler(request, reply) {
var req = request.raw.req
var res = request.raw.res
reply.close(false)
handler(req, res)
}
}
legacy_server.listen(8081)
express_app.listen(8082)
server.start()
This seems to work, although I would love if somebody who knew Hapi well could confirm that it is bug-free.
$ # Hit the Hapi application
$ curl localhost:8080/
I am a Hapi handler
$ # Hit the http application
$ curl localhost:8081/
I am a standard handler
$ # Hit the Express application
$ curl localhost:8082/
I am an Express app
$ # Hit the http application hosted by Hapi
$ curl localhost:8080/legacy
I am a standard handler
$ # Hit the Express application hosted by Hapi
$ curl localhost:8080/express
I am an Express app