I am connecting to an authentication server which is returning the credentials and calling to my call back method. How do I pass the authenticated values back to the html to render?
Here is my code
function getHomePage()
{
// alert("here in ajax call")
$.ajax({
url: "/calloidcServer",
headers:{
'Access-Control-Allow-Methods':'POST, PUT, OPTIONS, DELETE, GET',
'Access-Control-Allow-Origin':['https://localhost:3000','https://localhost:9031'],
'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept',
'Access-Control-Allow-Credentials':true,
'Content-Type':'application/json',
},
type: "GET",
success: function (resp) {
console.log(resp)
$('#testoidc').append(resp);
},
error: function (resp, status, error) {
}
});
}
app.get("/calloidcServer",function (req, res, next) {
console.log('-----------------------------');
console.log('/Start login handler');
next();
},
passport.authenticate('oidc',{scope:"openid"})
)
app.get('/callback',(req,res,next) =>{
console.log(" call back from auth server here")
passport.authenticate('oidc',{ successRedirect: '/user',
failureRedirect: '/' })(req, res, next)
}
)
app.get ("/user",(req,res) =>{
res.header("Content-Type",'application/json');
var id_token_decode=jwt_decoder(req.session.tokenSet.id_token);
var decoded = jwt_decoder(req.session.tokenSet.access_token);
console.log(id_token_decode)
console.log(decoded);
console.log(path.join(__dirname + '/public/citizenHome.html'))
res.redirect("/citizenHome.html")
//res.send(JSON.stringify({tokenset:req.session.tokenSet,userinfo:req.session.userinfo},null,2));
})
When I redirect to citizenHome.html, I want to send back some data to it to show in the html? I have not used any view engine.
I am not sure if you can pass values to the HTML directly, but you can use any view-engine with Node.js that can help you pass values from the routes and render the page as you want.
You can use EJS, JADE or Pug.
Related
i am trying to implement a work flow, where, when the user logs in, the user credentials is posted to one of the routes in express via ajax to check if the user exists, if the user exists, the express route will send back a message "authorised" to the ajax call, and the success callback is invoked where another ajax call sends a header along with data to the express route(/reroute). This express /reroute api is trying to res.redirect to another route /homepage. Inside the /homepage route i am attempting to display a html file using res.sendfile, and the res.sendfile is not working.
my login ajax call
$(document).on("click", "#login", (e) => {
const email = $('#logemail').val().trim();
const pass = $('#password').val().trim();
$.ajax({
url: "http://localhost:4000/checkuserexists",
type: "POST",
dataType: "JSON",
data: {
email: email,
pass: pass
},
success: function(data, textStatus, request) {
console.log(data)
if (data.message === "authorised") {
const token = request.getResponseHeader('access-token');
localStorage.setItem("access-token", token);
$.ajax({
url: "http://localhost:4000/reroute",
type: "GET",
dataType: "JSON",
beforeSend: function(xhr) {
xhr.setRequestHeader('access-token', token);
},
data: {
redirectTo: 'homepage'
},
success: function(data) {
console.log(data + " from ajax ")
}
})
} else {
$('.alertbox').show();
$('.alertbox').text("User unauthorised");
}
}
})
})
my express route (/reroute)
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
if (req.header('access-token')) {
const token = req.header('access-token');
const redirectTo = req.query.redirectTo;
if (redirectTo === 'homepage') {
res.setHeader('access-token', token)
res.redirect('/homepage')
}
}
})
module.exports = router;
my homepage route
const express = require('express');
const path = require('path');
const token_middleware = require('../middlewares/jwtauth');
const router = express.Router();
router.use(express.static(path.join(__dirname, "../public")))
router.get('/', token_middleware, (req, res) => {
if (req.status === "exists") {
res.sendFile(path.join(__dirname, "../public/homepage.html"));
} else {
res.redirect('/');
}
})
module.exports = router;
You're requesting the URL with Ajax.
The browser asks for /reroute and gets a redirect to /homepage.
It then asks for /homepage and gets an HTML document.
It passes that HTML document to the JavaScript engine and jQuery tries to parse it as JSON (it ignores the Content-Type because you said dataType: "JSON") and errors.
If you want to do this with Ajax, then don't redirect. Return some JSON that tells your code the login was successful. Then you can navigate with client-side JS and the location object.
If you want to redirect, then use a regular form submission and not Ajax.
I am using the below code to post some JSON data to a url and in response I am getting a HTML page.
var request = require('request');
request.post({
url: "URL OF A WEBSITE",
headers: {
"Content-Type": "application/json"
},
body: {
my_json_obj
},
json:true
}, function(error, response, body){
console.log(error);
console.log(JSON.stringify(response));
console.log(body);
});
This code works fine I am getting a HTML page in the body tag.
I want to load that HTML page in the browser. How should I do that, I know this is a very basic question but I am very new to node.js someone please help me?
Follow the Express "Hello World" example and use your request call in the route handler:
/*jslint node:true, esversion:6*/
"use strict";
const request = require("request"),
express = require("express"),
app = express();
let my_json_obj = {},
URL_OF_WEBSITE = "http://www.google.com";
app.get("/", function (req, res) {
request.post({
url: URL_OF_WEBSITE,
headers: {
"Content-Type": "application/json"
},
body: {
my_json_obj
},
json: true
}, function (error, response, body) {
if (error) {
console.log(error);
return res.sendStatus(404);
}
console.log(JSON.stringify(response));
console.log(body);
res.send(body);
});
});
app.listen(3000, function () {
console.log("Example app listening on port 3000!");
});
node.js does have its own way to make a server, but for the sake of brevity and ease I just recommend using Express.
Are you using Express js? It would make things a lot easier when working with Node js apps.
Look into Express routing:
https://medium.com/javascript-scene/introduction-to-node-express-90c431f9e6fd
You can create an Express boilerplate in the terminal by using the command:
express yourappname
you can then put your html/css/js files inside the express-app -> 'public' folder that you just generated.
After that you create routes inside your app.js by doing something like:
// exampledomain.com/
// Loading the file index.html when user navigates to '/'
app.get('/', function(req, res){
res.sendFile(path.join(__dirname + '/public/index.html'));
});
// or
// exampledomain.com/getFileURL
// POST request (from your ajax) to '/getFileURL'
// which will then load the about.html file into the browser
app.post('/getFileURL', function(req, res){
// Do more JSON/data handling & Node js stuff here then
// send something back
res.sendFile(path.join(__dirname + '/public/about.html'));
});
There're many more useful functions with Express js, but I think Routing is what you need right now.
p.s. Very useful tools to look into when working with Node js:
Postman (Testing ajax/express/Nodejs routes and responses)
Nodemon (Starting Nodejs server automatically on save)
I'm trying to build a stateless API using JWT. I have a middleware function in my Router which checks if the JWT has expired, if it has, a new Token with a new timestamp is generated on the fly.
I would like to pass the new token along with the response in the JSON Object. My current approach is like this, but it of course doesn't work:
router.use(function (req, res, next) {
// JWT Expired
// Generate new JWT
res.write(JSON.stringify({token: token});
next();
});
router.get('/securedRoute' function(req, res) {
// Fetch data
res.json({data: data});
});
:
// Output should be:
{token: 'erg34jlkgjre.3f4fknlj.34f3', data: ['sdfa', 'sdf']}
It would be nice to find a way, where I don't have to alter all of my existing code and check if there is a new token.
Thanks for your help!
One option would be to add the authorization token in the response header:
router.use((request, response, next) => {
response.setHeader('Token', token);
next();
});
router.get('/securedRoute', (request, response) => {
response.json({ data: data });
});
Alternatively, you could always add the token to the request and then conditionally add the request.token into all of your routes like the previous answer suggested. Unfortunately that would mean that you need to modify all of your routes.
As an alternative you could override the response.json method and manually inject the token if it exists. In doing so, you wouldn't need to modify any of your routes.
router.use((request, response, next) => {
request.token = token;
((proxied) => {
response.json = function (data) {
if (request && request.token) {
data.token = request.token;
}
return proxied.call(this, data);
};
})(response.json);
next();
});
router.get('/securedRoute', (request, response) => {
response.json({ data: data });
});
In the example above, the response.json method is overridden in the middleware. This is done by passing a reference to the old response.json method and then calling it after conditionally injecting the token into the payload.
The answer is assuming you want to achieve that in same method
Rather than writing the token in middleware do something like
(req,res,next)=>{
req.token = newToken;
next();
}
And in your route
res.json(req.token ? {token:req.token,data:data} : {data:data});
I am trying to send my form data as json but not able to do so can any one help please....
my ts,
headers.append('Content-Type', 'application/x-www-form-urlencoded')
this.http.post(this.header1+'login', JSON.stringify(form), { headers: headers })
.subscribe(
response => {
if (response.json().error_code == 0) {
// console.log(response.json().data[0].profile_id);
if (response.json().data[0].profile_id) {
localStorage.setItem('social', JSON.stringify(response.json().data[0]));
}
this.toastr.success('Loggedin successfully');
this.router.navigate(['/demo/profile']);
}
else {
this.toastr.error('Email or Password is wrong');
}
});
}
but i am not able to see any data going to server from network
i cleared it by including the following steps in my node.js
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.header('Access-Control-Allow-Origin', '*');
// Request methods you wish to allow
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.header('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.header('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
res.header('Access-Control-Allow-Headers', 'Content-Type, application/json');
next();
});
I am learning Angular and Node and I am trying to figure out how to have my Angular app hit a separate app hosting a rest API.
The request body is displayed as
{ '{"name":"test"}': '' }
and I expect it to be displayed as
{ "name" : "test"}
This is the front-end app that sends the post request.
$http({
method: 'POST',
url: 'http://localhost:8080/api/test',
data: {
"name": 'test'
},
dataType: "json",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
});
It is hitting the route defined as
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.all('/', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
router.post('/test', function(req, res) {
var name = req.body.name;
console.log(req.body);
});
I expect the issue to be with the content-type being application/x-www-form-urlencoded but I cannot figure out how to allow cors with application/json.
JSONP can be used for performing CORS requests (more about json/jsonp here What are the differences between JSON and JSONP?), and in AngularJS documentation - jsonp using $http