Express js authorization value undefined - javascript

I have two ports opened: 3000 and 4000. I want to pass the authorization header from 3000 and receive it on port 4000.
I'm passing authorization value from 3000 port
app.get('/',function(req,res){
console.log('redirect');
res.header('Authorization', 'my sample');
res.redirect('http://localhost:4000/api/oauth2');
});
Receive on 4000 port
app.get('/api/oauth2', (req, res)=> {
console.log(req.headers.authorization); // undefined
res.end('i reached');
})
How would I receive this value from 3000 to 4000 port?

You can either return the '/' request with a .html file that makes a request on the client side, or you can set the auth token in the url query.

You will have to use request package from npm which is a http client.
npm install request
Import request module.
const request = require('request');
let options = {
url: "http://localhost:4000/api/oauth",
headers:{
authorization: "your_authorization_token"
}
request.get(options, (err, response, body)=>{
// Handle response
})

Related

How to send token from server to client?

I have express app, running on port 8000, I also have react on port 3000.
I am trying to implement google oauth.
This is what I did.
I try to send get request to my api endpoint,
then my express server redirect user to google Sign in.
And then, how can I send token from server to client from get request?
Here's my express code.
I try to send cookies directly from the server,
but I don't know why the cookies is not available on port 3000 which is my react app.
Is there any neat way to send jwt to client?
router.get(
"/google/callback",
passport.authenticate("google", {
scope: ["profile", "email"],
failureRedirect: "/login",
session: false,
}),
(req, res) => {
const payload = {
id: req.user.id,
};
jwt.sign(payload, secret, { expiresIn: tokenLife }, (err, token) => {
if(err) {
console.log('error', err)
}
const jwt = `Bearer ${token}`;
console.log('ini token', token)
const htmlWithEmbeddedJWT = `
<html>
<script>
// Save JWT to cookie
// document.cookie = 'token=${jwt};'
document.cookie = 'token=${jwt}; SameSite=None; Secure'
// Redirect browser to root of application
window.open('http://localhost:3000/login', '_self')
</script>
</html>
`;
res.send(htmlWithEmbeddedJWT);
});
}
);
It is not available because you have responded to the google call and then redirected the page on a client to the localhost apparently cookies will not be available.
The common way to handle auth in such cases is to define a success redirect that will expect to receive somekind of a token in query params.

Node.js HTTP Server- Taking long time to load and is not sending data

I am learning node.js, While using HTTP module i tried to create by own server as per instruction of video tutor but my server is not sending any response at port 3000 and port 8000.
*
const http = require('http');
const server = http.createServer((req, res) => {
if(req === '/'){
res.write('Hello world, first program in server using http module');
res.end();
}
if(req === '/api/courses'){
res.write(json.strigify([1,2,3]));
res.end();
}
});
server.listen(8000);
console.log('Listening #port 8000');
*
The strict comparison req === '/' is comparing a request object with a string, a comparison which will never be true.
You likely meant to use: req.url === '/'

Need help to create the server.js to work around the CORS issue

So, I need to hit an API and render the response in a html element. I have my app.js doing this:
let url = 'http://localhost:80/db/abc/query/';
class abc extends Component {
state {userinput:""}
getResponse = () => {
axios.get(url+this.state.userinput, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
this.setState({results: response.data})
});
}
render () { //ignore the render for now
return ()
}
}
export default abc;
But since I was getting the CORS error, I created a server.js & started the proxy using # node server.js command. But for some reason I keep getting Error 500 back from the API.
Server.js
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.use('/', function(req, res) {
var url = 'https://' +
req.get('url').replace('localhost:80', 'my-real-host-fqdn:8122') +
req.url
req.pipe(request({ qs:req.query, uri: url })).pipe(res);
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
I call my getResponse() on a button click, which is working but not included in the excerpt above.
Error Messages:
GET http://localhost/db/abc/query/<userinput> 500 (Internal Server Error)
createError.js:17 Uncaught (in promise) Error: Request failed with status code 500
Errors with proxy server:
CORS-enabled web server listening on port 80
TypeError: Cannot read property 'replace' of undefined
OR
CORS-enabled web server listening on port 80
ReferenceError: request is not defined
I am not very familiar with the server.js file and using express. How does this work, and have I made any mistakes here?
So what did the trick for me was removing this line from my server.js:
req.pipe(request({ qs:req.query, uri: url })).pipe(res);
Posting this here so it helps someone with a similar issue.
Thanks for trying to help guys!!
to get host, use req.get('host'). Seems like req.get('url') is the issue.
app.get('/one/two', function (req, res) {
var url = req.url;
}
How to get the full url in Express?

Client program for continuous talking to an echo server in nodejs

I'm an absolute beginner in nodejs. I've created an echo server in nodejs. And honestly i would say, i followed few youtube tutorials for this. There is nothing wrong with the server code. I want to create a client program to talk to this server. I dont want to use telnet client or any such thing. And by 'continuous' I mean the server and client should stay connected till I close the server manually using ctrl+c. Here's my server.js.
const express = require('express');
const bodyParser=require('body-parser');
var server=express();
server.use(bodyParser.urlencoded({extended: false}));
server.use(bodyParser.json());
server.post("/", function (req, res) {
console.log("I got: "+req.body.message);
res.send(req.body.message);
});
server.listen(3000, function() {
console.log("Express echo server is listening on port 3000");
})
I do not say hey write the code for me. In fact I tried also. Here's my client.js
var request = require('request');
var arg="";
process.argv.slice(2).forEach(function (val, index, array) {
arg+=val +" ";
});
request.post({
url: "http://localhost:3000",
json: true,
body: {message: arg}
}, function (err, response, body) {
if(!err && response.statusCode==200) {
console.log(body);
}
});
But client sends data only once that too using command line argument.
node client.js hello
PS: I'm using these npm modules express, body-parser and request
What you made is a HTTP Server using express.
The server runs alright, but the client closes because you are only making a single request to the server. So what is happening is expected behaviour.
So, there are multiple ways,
The most simple way would be, using readline or some other to continuously read the lines that you type And sending it to the server:
const request = require('request');
const readline = require("readline").createInterface({
input: process.stdin,
output: process.stdout
});
readline.setPrompt('msg: ');
readline.prompt();
readline.on('line', function(input) {
if(input === 'close') return readline.close();
request.post({
url: "http://localhost:3000",
json: true,
body: {message: input}
}, function (err, response, body) {
readline.prompt();
});
}).on('close', function() {
console.log('Closed');
process.exit(0);
});
But the proper way would be using sockets like socket-io to make a persistent connection between the server and client. Read here for more information.

http.createServer() vs http.request()

I think I understand this below code:
var assert =require("assert");
var http = require("http");
var server = http.createServer(function(req, res){
res.writeHead(200, {"Content-Type" : "text/HTML"});
res.write("hello, world.\r\n");
res.end();
});
server.listen(8000, function(){
console.log("Listening on port 8000");
});
We create a server and set it up to listen on port 8000 and when i go to page localhost:8000 in the browser I think it initiates a request to the server for something(can someone help me specify what that is) then the server responds with a header and "hello world"
the next part I'm not so sure of:
var req = http.request({
port : 8000
}, function(res){
console.log("HTTP header:", res.headers);
res.on("data", function(data){
console.log("Body:", data.toString());
assert.equal("hello, world.\r\n", data.toString());
assert.equal(200, res.statusCode);
// server.unref(); //client disconnected...sever stop listening
})
})
req.end()
^^^ Is this server sending a request to the browser
I know the doc says
Node maintains several connections per server to make HTTP requests. This function allows one to transparently issue requests.
does that mean that server is sending a request. you could randomly send a request to a client? and if so how does it get the data? Doesn't there have to be some type of initiation from the browser/ client to send over the data how does res.on("data" ) get the data?

Categories

Resources