I am new to node.js. I am not sure whether it is my code or my computer system causing this problem. The localhost:3000\login refuse to connect.
My code
const http = require('http');
var server = http.createServer((req,res)=>{
body = [];
req.on('error',(err)=>{
console.log(error);
}).on("data",(chunkdata)=>{
body.push(chunkdata);
console.log(chunkdata.toString());
}).on("end",()=>{
body = Buffer.concat(body).toString();
if(req.method =="POST"){
if(req.url=="/login"){
console.log(body)
var user = JSON.parse(body);
const {username,password} = user;
res.statusCode =200;
res.setHeader("Content-Type","application/json");
res.write("Your usename is "+username +"and password is "+password );
res.end();
}
}
})
})
server.listen(3000,() => {
console.log("Server connected");
});
Can you help me solve this problem?
I try using Postman and it working fine
If you directly trying to go localhost:3000\login on your browser that means you are making a GET request but you defined /login route as POST in your code.
Related
My former server.js is like:
After running the server I could see my index.html
var connect = require('connect');
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(5000, '192.168.xx.xx', function(){
console.log('Server running on 5000');
});
I want to create http login and password to secure the website, so I found online the information of http module: if I put right login and password, I could see congratulations message:
var http = require('http');
var server = http.createServer(function(req, res) {
// console.log(req); // debug dump the request
// If they pass in a basic auth credential it'll be in a header called "Authorization" (note NodeJS lowercases the names of headers in its request object)
var auth = req.headers['authorization']; // auth is in base64(username:password) so we need to decode the base64
console.log("Authorization Header is: ", auth);
if(!auth) { // No Authorization header was passed in so it's the first time the browser hit us
// Sending a 401 will require authentication, we need to send the 'WWW-Authenticate' to tell them the sort of authentication to use
// Basic auth is quite literally the easiest and least secure, it simply gives back base64( username + ":" + password ) from the browser
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
res.end('<html><body>Need authorization</body></html>');
}
else if(auth) { // The Authorization was passed in so now we validate it
var tmp = auth.split(' '); // Split on a space, the original auth looks like "Basic Y2hhcmxlczoxMjM0NQ==" and we need the 2nd part
var buf = new Buffer(tmp[1], 'base64'); // create a buffer and tell it the data coming in is base64
var plain_auth = buf.toString(); // read it back out as a string
console.log("Decoded Authorization ", plain_auth);
// At this point plain_auth = "username:password"
var creds = plain_auth.split(':'); // split on a ':'
var username = creds[0];
var password = creds[1];
if((username == 'admin') && (password == 'admin')) { // Is the username/password correct?
res.statusCode = 200; // OK
res.end('<html><body>Congratulations, feel free to explre!</body></html>');
}
else {
res.statusCode = 401; // Force them to retry authentication
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
// res.statusCode = 403; // or alternatively just reject them altogether with a 403 Forbidden
res.end('<html><body>You shall not pass</body></html>');
}
}
});
server.listen(5000, function() { console.log("Server Listening on http://localhost:5000/"); });
I am new to nodejs, I want to know how to combine this 2 js? In order to realize my function of adding authorization to my web.
Could I do something to show my index instead of showing congratulation message after putting the login and password?
Thanks a lot.
In order to show HTML page instead of congratulation message, you can follow these steps:
Get request path by req.url, such as / or /introduction.html.
According to the above path, read the corresponding HTML file in server disk, using fs.readFile().
Return HTML file content to browser if the read is successful. Otherwise, return 404 error page.
Here is some example code for above steps:
if((username == 'admin') && (password == 'admin')) { // Is the username/password correct?
res.statusCode = 200; // OK
// res.end('<html><body>Congratulations, feel free to explre!</body></html>');
var requestURL = req.url; // e.g. / or /a or /a.html
var requestFilePath = getFilePathFromRequestURL(requestURL); // you need to implement this logic yourself, such as "/" mapping to "./index.html"
fs.readFile(requestFilePath, function(error, data) {
if (error) {
res.statusCode = 404;
res.write('File not found.');
} else {
res.statusCode = 200;
res.write(data);
}
res.end();
});
}
However, unless you want to write some low-level node.js code to better understand this language, I highly recommend using node.js web framework such as Express. Serve HTTP request using low-level node.js would be tedious, especially in production code.
Also, please note that using WWW-Authenticate Basic for authentication is neither secure nor user-friendly. You need some other way to implement authentication, such as JSON Web Tokens
Struggling with one issue on a simple Websockets example using node
I originally used this Websocket/node tutorial as a starting-point. This is my first attempt, so I knew almost nothing when I started.
"Connection closed beforeā¦ handshake" is a very common issue, to which there seems to be no definitive answer. From the many SO questions I've spent a day trying answers and suggested code, to no effect, including checking my proxy and allowing localhost (no joy).
Here's my code, including an (incomplete) front-end (I used npm install websocket in my local dir, not using socket.io, and although I'm willing to try I'd rather get this working first):
server.js
"use strict";
let http = require('http');
let fs = require('fs');
let server = http.createServer(function(request, response) {});
const PORT=8080;
fs.readFile('client/index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
console.log(`${(new Date())} Server is listening on port ${PORT}`);
}).listen(PORT);
});
let WebSocketServer = require('websocket').server;
let wsServer = new WebSocketServer({
httpServer: server
});
wsServer.on('request', function(r){
// runs on connection
let connection = r.accept('echo-protocol', r.origin);
let count = 0;
let clients = {};
// Specific id for this client & increment count
let id = count++;
// Stores the connection method for looping through & contacting all clients
clients[id] = connection;
console.log(`${(new Date())} Connection accepted [${id}]`);
connection.on('message', function(message) {
// The string message sent to us
let msgString = message.utf8Data;
// Loops through all clients
for(let i in clients){
// Sends a message to the client with the message
clients[i].sendUTF(msgString);
}
});
connection.on('close', function(reasonCode, description) {
delete clients[id];
console.log(`${(new Date())} Peer ${connection.remoteAddress} disconnected.`);
});
});
index.html
<body>
<h1>Hello Web Sockets</h1>
<div id="chatlog"></div>
<input type="text" id="message">
<input type="button" value="Send" onclick="sendMessage()">
<!-- lose 'onclick' later -->
<script>
"use strict";
let ws = new WebSocket('ws://localhost:8080', 'echo-protocol');
function sendMessage(){
console.log(ws);
let message = document.getElementById('message').value;
console.log(message);
ws.send(message);
}
ws.addEventListener('message', function(e){
// The data is the message being sent back
let msg = e.data;
// Append the message to the DOM
document.getElementById("chatlog").innerHTML += `<br>${msg}`;
});
</script>
</body>
I have HTTP Proxy based on Node.js which transforms response body on fly in stream fashion. For instance, my proxy works like nginx, which compresses (using libz for gzipping) response body.
But I have open question: What if error occures on upstream connection during the data exchange. How to notify client about en error, when response have already been sent and transmitting body is in progress. Complexity of error determination on client side based on fact that Content-Length is absent in response due to source and transformed data mismatch.
To clarify some details I added a simple piece of code:
var express = require("express");
var http = require("http");
var url = require('url');
var webApp = express();
var httpServer = webApp.listen(8080, function () {
console.log("server started on ", 8080, " port");
});
webApp.get("*", function(req, res) {
var targetRequest = http.get(req.originalUrl, function (upstreamResponse) {
if (upstreamResponse.statusCode != 200) {
res.status(500).send("Internal Server Error");
return;
}
upstreamResponse.on("data", function (chunk) {
/// transform chunk and send it to the client
res.write(chunk);
});
upstreamResponse.on("end", function () {
res.end();
});
/// upstream connection error occured
upstreamResponse.on("error", function (error) {
/// How to properly notify client
/// about error ????
/// ????
});
});
});
Actually, the only one way to notify clients about some issues is just to drop downstream connections.
This is my node.js file, what's happening is, a user inputs an id and it gets sent to the server-side, which the server then takes and searches it through an api on a third-party. The problem I am having is, the response from the initial id sent by the user gets res.end before I get the info back from the api, thus getting a big fat undefined or an empty string on the client side. How can I make it so the res.end waits until it receives the data from the api and then sends it to the client? Or am I going at it entirely wrong and shouldn't be doing it this way?
var http = require('http');
var https = require('https');
var url = require('url');`
http.createServer(function (req, res) {
var id = url.parse(req.url,false).query;
var realId = getInfoFromApi(id);
res.setHeader('Access-Control-Allow-Origin', '*');
res.writeHead(200);
res.end(JSON.stringify(realId));
}).listen(3000, '127.0.0.1');
function getInfoFromApi(id) {
var url = "https://random.com/" + id + "?api_key=blabla";
var test = https.get(url, function(res) {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
var theId = JSON.parse(body)
console.log("Got response: ", theId);
});
}).on('error', function(e) {
console.log("Got error: ", e);
});
return test;
}
Any info into what I should be looking or resources that would help me would be greatly appreciated, thanks in advance for any help.
Also as a bonus question, should I be using POST method instead of GET from server to api-server? Or does POST privacy only matter from client to server? I'm just curious if clever clients would be able to access the server http.requests if I use GET instead of POST or if it even matters at all since it's from the server and not the client.
Oh and another thing, I was debating if I should use https.createServer since I have to use https for https.get, that way I could remove the http module from require and only use https. Is there any big difference in performance or anything if I do that?
Thanks again in advance.
EDIT:
http.createServer(function (req, res) {
var id = url.parse(req.url, false).query;
var link = "https://random.com/" + id + "?api_key=blabla";
var testo = https.get(link, function (rez) {
var body = '';
rez.on('data', function (chunk) {
body += chunk;
});
rez.on('end', function () {
var endRes = body
res.setHeader('Access-Control-Allow-Origin', '*');
res.writeHead(200);
res.end(endRes);
});
}).on('error', function (e) {
console.log("Got error: ", e);
});
}).listen(3000, '127.0.0.1');
I managed to change it like this after I read into callbacks. Thank you for that. It works fine now, so happy, thanks again. My question now though is, does this work flawlessly if dozens or hundreds of people are searching at the same time? Does each client connected to the server get their own seperate function thing that runs at their own pace without interfering with others? Thanks again for all your help.
Note: My question may be very similar to this question, but the solution is not working for me.
My problem is the same as the original poster. I need to access an external resource, and I need to proxy to it to get around cross domain security restrictions. I had also referenced this sample blog post: http://nthloop.com/blog/local-dev-with-nodejs-proxy/
The proxy is working to load external resources (anything containing 'cgi' in the url). But with this code, I am no logner able to hit local (static) files with the connect module. Times out, no error messages, etc...
I am posting the full code of my server.js file:
var httpProxy = require('http-proxy');
var connect = require('connect');
var endpoint = {
host: '11.0.0.120',
port: 8081
};
var proxy = new httpProxy.RoutingProxy();
var app = connect()
.use(function(req, res) {
if (req.url.indexOf('cgi') >= 0) {
proxy.proxyRequest(req, res, endpoint);
} else {connect.static(__dirname)};
})
.use(connect.static(__dirname))
.listen(8182);
This question's solution seemed to state that I needed to include an else condition. It doesn't wok without or without one.
Thanks for any help!
You can use next() to let request flow to the next middleware -
var app = connect()
.use(function(req, res, next) {
if (req.url.indexOf('cgi') >= 0) {
proxy.proxyRequest(req, res, endpoint);
} else {
next();
)};
})
.use(connect.static(__dirname))
.listen(8182);
Oops, got it working just by swapping the use(connect...) function to the first call. Don't know why this worked or if it is the best approach. Also, didn't need the else statement.
If someone can give a better explanation I can accept their answer. Here's my working code:
var httpProxy = require('http-proxy');
var connect = require('connect');
var endpoint = {
host: '11.0.0.120',
port: 8081
};
var proxy = new httpProxy.RoutingProxy();
var app = connect()
.use(connect.static(__dirname))
.use(function(req, res) {
if (req.url.indexOf('cgi') >= 0) {
proxy.proxyRequest(req, res, endpoint);
}
})
.listen(8182);