I'm running a simple nodejs server on my localhost on port :3434
const cors = require('cors');
const app = require('express')();
const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
app.get('/ping/:anystring', (req, res) => {
console.log(req.params['anystring']);
res.send({
anystring: req.params['anystring']
})
});
app.listen(3434);
and I'd like to perform some ajax call from a website of mine.
I tried to configure the router port forwarding like so:
- name service: mylocalserver
- porta ragnge: 3434
- local ip: 192.168.1.19
- local port: 3434
- protocol: BOTH
but when I do
fetch(publicIP:3434/ping/hello).then(res => {
console.log(res);
})
I get error 404
Might anyone help me telling what I'm doing wrong?
You can't access your localhost server outside of your LAN unless you create a tunnel. I use ngrok.
There is an npm package for ngrok, but I couldn't get that one working, so I just manually start the server from terminal whenever I need to test an API.
Also you'll need http.
add this to your app.js:
const http = require('http');
const newPort = //your port here (needs to be a different port than the port your app is currently using)
const server = http.createServer(function(req, res) {
console.log(req); //code to handle requests to newPort
res.end('Hello World);
});
app.listen(newPort, function() {
console.log(`ngrok listening on ${newPort}`);
});
Now in terminal, after installing ngrok, use this ngrok http newPort where newPort = your port
You can view requests sent to your server by going to localhost:4040 (this might change depending on your system)
To send a request to your localhost, do this:
- name service: mylocalserver //not sure
- porta ragnge: ???
- local ip: //ngrok gives you a url in terminal when you start the server (I'm not sure if you can reference an IP)
- local port: newPort
- protocol: http //(ngrok gives you a different url for http and https)
You can use local tunnel
It maps your port on the localhost to a web url whithout the need to change your code
Related
I am using nodejs to handle my server and I have a website on it.
I recently set up SSL and want to redirect http to https but couldn't do it. I tried every approved solution on stackoverflow but none of them are working.
Here is my server app:
const express = require('express');
const app = express();
const https = require('https');
const fetch = require('node-fetch');
const bcrypt = require('bcrypt');
const hogan = require('hogan.js');
const fs = require('fs');
const optionSSL = {
key: fs.readFileSync("./etc/ssl/myssl.pem"),
cert: fs.readFileSync("./etc/ssl/myssl.crt")
};
//app.listen(80, () => console.log("Listening at 80"));
app.use(express.static('public', {
extensions: ['html', 'htm'],
}));
app.use(express.json({limit: '1mb'}));
app.use(express.urlencoded({ extended: false }));
https.createServer(optionSSL, app).listen(443, "mydomain.com");
The things that I tried:
Automatic HTTPS connection/redirect with node.js/express
Redirect nodejs express static request to https
How do you follow an HTTP Redirect in Node.js?
https.createServer(optionSSL, app).listen(443, "mydomain.com");
You are listening on port 443, which is the HTTPS port.
If you want to redirect from HTTP then you need to listen on the HTTP port (and not attach certificates to it).
The simplest way to do this would be to run a completely different server (dedicated to performing the redirects) on port 80. You could write one in Node.js, or you could just use something off-the-shelf like nginx or lighttpd.
Here is my solution to this issue:
const httpApp = express();
const http = require('http');
httpApp.get("*", function(req, res, next) {
res.redirect("https://" + req.headers.host + req.path);
});
http.createServer(httpApp).listen(80, function() {
console.log("Express TTP server listening on port 80");
});
https.createServer(optionSSL, app).listen(443, function() {
console.log("Express HTTP server listening on port 443" );
});
Thank you #Quentin for giving me idea of listening on two ports.
I'm new to web design and am trying to create and a simple local server and a local client. I fear I have fallen down the rabbit hole as I'm going round in circles.
I have made a simple Express node.js server:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var port = 3000;
app.listen(port, function() {
console.log("Listening on port: " + port);
});
app.get('/', function(req, res) {
console.log(req);
res.send('Get request received at "/"');
});
app.post('/quotes', function(req, res) {
console.log(req);
// do something
});
and I have a javascript client:
const url = "http://localhost/3000";
fetch(url)
.then((resp) => resp.json())
.then(function(response) {
let data = response.results;
console.log(data);
//do something
})
.catch(function(error) {
console.log(JSON.stringify(error));
});
called from an index.html file.
When I type http://localhost:3000 into my (chrome) browser I get
'Get request received at "/"'
displayed in the browser and a very long req displayed in the node.js console just as I expect.
However when I load the index.html into the browser it doesn't work.
Originally the index.html file was in a different directory to the node.js server and I got the error:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
So I moved it into the same directory as the node.js server and now get this error:
Failed to load resource: net::ERR_CONNECTION_REFUSED
in the browser console and no output in the node console.
Seems I needed to enable cors on my server. npm install cors and this answer solved my problem.
How to allow CORS?
I would replace
const url = "http://localhost/3000";
with const url = "http://localhost:3000";
I've got a React app that via an API pulls data from a separate database.
When I run it locally, the app is one port and the API is on another port.
Since when I make AJAX calls in the app to the API, I need to include the URL where the API can connect.
It works if I hardcode the separate port (e.g., the app is on http://localhost:3000 and the API on http://localhost:3100, making the AJAX url call to the API http://localhost:3100/api/trusts).
However, since the app and API are on different ports, I can't make the AJAX url a relative path because it erroneously sends the AJAX call to http://localhost:3000/api/trusts and not http://localhost:3100/api/trusts.
How do I get them to run on the same port?
Thanks!
Here's my server.js:
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var path = require('path');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//set our port to either a predetermined port number if you have set it up, or 3001
var port = process.env.PORT || 5656;
//db config
var mongoDB = 'mongodb://XXX:XXX!#XXX.mlab.com:XXX/XXX';
mongoose.connect(mongoDB);
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
//body parsing
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// allow cross-browser
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
});
// handling static assets
app.use(express.static(path.join(__dirname, 'build')));
// api handling
var TrustsSchema = new Schema({
id: String,
name: String
});
var Trust = mongoose.model('Trust', TrustsSchema);
const trustRouter = express.Router();
trustRouter
.get('/', (req,res) => {
Trust.find(function(err, trusts) {
if (err) {
res.send(err);
}
res.json(trusts)
});
});
app.use('/api/trusts', trustRouter);
//now we can set the route path & initialize the API
router.get('/', function(req, res) {
res.json({ message: 'API Initialized!'});
});
app.get('/*', function (req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(port, function() {
console.log(`api running on port ${port}`);
});
Below is the AJAX call I'm trying to make that doesn't work because the relative path is appended to the app's port (i.e., http://localhost:3000/) and not the API's port (i.e., http://localhost:3100/):
axios.get("/api/trusts")
.then(res => {
this.setState({trusts: res.data});
})
.catch(console.error);
To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example:
"proxy": "http://localhost:4000",
This way, when you fetch('/api/todos') in development, the development server will recognize that it’s not a static asset, and will proxy your request to http://localhost:4000/api/todos as a fallback. The development server will only attempt to send requests without text/html in its Accept header to the proxy.
"Keep in mind that proxy only has effect in development (with npm start), and it is up to you to ensure that URLs like /api/todos point to the right thing in production."
Note: this feature is available with react-scripts#0.2.3 and higher.
More details here: https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/template/README.md#proxying-api-requests-in-development
Trying to test an endpoint in express But keep getting 404 error.
var express = require("express")
var app = express()
//var http = require('http').Server(app)
app.get('/', function(req,res){
res.send('ok from end point')
})
var port = process.env.PORT|| 8080
var localhost = 'someLocalHost.med.gov'
console.log({'localhost':localhost,
'post':port})
//
app.listen(port,localhost,function(err){
if (err){
console.log('err')
}
else {
console.log('Listening')
}
})
When I go to
http://someLocalHost.med.gov:8080/
I get a 404 error
Localhost refers to 127.0.0.1. You can't just launch a server on any address that you want. If you're wanting to override localhost you can look into modifying your HOSTS file locally to setup an alias for localhost.
So I ended up http:// IP_ADDRESS:8080 and that took care of it.
I'm very new for this stuff, and trying to make some express app
var express = require('express');
var app = express();
app.listen(3000, function(err) {
if(err){
console.log(err);
} else {
console.log("listen:3000");
}
});
//something useful
app.get('*', function(req, res) {
res.status(200).send('ok')
});
When I start the server with the command:
node server.js
everything goes fine.
I see on the console
listen:3000
and when I try
curl http://localhost:3000
I see 'ok'.
When I try
telnet localhost
I see
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'
but when I try
netstat -na | grep :3000
I see
tcp 0 0 0.0.0.0:3000 0.0.0.0:* LISTEN
The question is: why does it listen all interfaces instead of only localhost?
The OS is linux mint 17 without any whistles.
If you don't specify host while calling app.listen, server will run on all interfaces available i.e on 0.0.0.0
You can bind the IP address using the following code
app.listen(3000, '127.0.0.1');
If you want to run server in all interface use the following code
app.listen(3000, '0.0.0.0');
or
app.listen(3000)
From the documentation: app.listen(port, [hostname], [backlog], [callback])
Binds and listens for connections on the specified host and port. This method is identical to Node’s http.Server.listen().
var express = require('express');
var app = express();
app.listen(3000, '0.0.0.0');
document: app.listen([port[, host[, backlog]]][, callback])
example:
const express = require('express');
const app = express();
app.listen('9000','0.0.0.0',()=>{
console.log("server is listening on 9000 port");
})
Note: 0.0.0.0 to be given as host in order to access from outside interface