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.
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.
I'm new to programming and created a weather app to practice React. I also created a Node server and a homepage (portfolio). So my tree look like this:
project
-portfolio(homepage with simple html file)
-weather(React)
-server.js
Inside the weather app I make a couple of API fetches to openweathermap.org. But it has come to my attention that my API key will be visible when I publish this app and that the best way to avoid that, is to make the call in the Node backend. How do I move data from the weather app to the server.js and vice versa? For example, the user will enter a zip code in the weather app. This zip code is used in the url to fetch the data. How would I make the zip code show up in the server? And then do I just perform all the fetches in the server?
My weather app code can be found at this previous question. I did make the modification suggested and now have two separate useEffect. React - API fetches - 2nd fetch uses data from 1st fetch?
Thank you for your help.
server.js
const express = require("express")
const app = express()
const path = require("path")
const port = process.env.PORT || 5000
app.use("/weather",express.static(path.join("weather/build")))
app.use("/",express.static(path.join("portfolio")))
app.listen(port, () => console.log("Working"))
If you're using API keys on your frontend, it will always be exposed to anyone who checks your network requests. If you insist on using the API key with frontend requests, you should atleast use the .env module in your React frontend and add your API keys there, making sure you commit your .env to your .gitignore so it won't get committed to your source code.
const port = process.env.PORT || 5000
I'm assuming you already know how to set this up since you're using it here.
OR
You could just reverse proxy your request with your API endpoint, store your API keys in your .env, and have your route make the API request to openweathermap.org-- successfully hiding your API keys from network analysis:
React Weather App => YOUR_API_ENDPOINT
YOUR_API_ENDPOINT =>
openweathermap.org
Parse data => Send response to Weather App
How do I move data from the weather app to the server.js and vice
versa? For example, the user will enter a zip code in the weather app.
This zip code is used in the url to fetch the data. How would I make
the zip code show up in the server? And then do I just perform all the
fetches in the server?
Pass it as a param in the url of the request and have your backend parse out the params from the url.
Weather App:
axios.get(`${YOUR_API_ENDPOINT}/zip/${DYNAMIC_ZIP_CODE_DATA}`) //basic example
Node
app.get("/zip/:zip", (req, res) => {
console.log('params: ', req.params.zip)
const zip = req.params.zip;
//make the API request here and pass in the zip
res.send(req.params)
})
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 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
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