I have server side rendering react app in which i have proxied all http calls to different port. Please see the code below for http proxy.
import proxy from "express-http-proxy";
const app = express();
const bodyParser = require("body-parser");
const http = require('http');
const httpProxy = require('http-proxy');
const PORT = process.env.PORT || 3001;
httpProxy.createServer({
target: 'ws://localhost:4000',
ws: true
}).listen(PORT); //Throws error since 3000 port is already used by //app.listen.
app.use(
"/api",
proxy("http://localhost:4000/", {
proxyReqOptDecorator(opts) {
opts.headers["x-forwarded-host"] = "http://localhost:4000/";
return opts;
}
})
);
app.post("/logger", (req, res) => {
logger.debug(req.body.data);
res.send({ status: "SUCCESS" });
});
app.listen(PORT, () => {
logger.debug(`Portal listening on ${PORT}`);
});
that means when i make any calls /api/endpoint it will redirect to localhost:4000/endpoint but will be seen in the network as http://localhost:3000/endpoint1
I want the same behaviour with websockets as well.
I am using new WebSocket(ws://localhost:3000/endpoint1); It should redirect to ws://localhost:4000/endpoint1.
and should be shown in network tab as ws://localhost:3000/endpoint1
Resolved it by using another library http-proxy-middleware
import httpproxy from "http-proxy-middleware";
import proxy from "express-http-proxy";
const app = express();
const bodyParser = require("body-parser");
const PORT = process.env.PORT || 3001;
const wsProxy = httpproxy('/ws', {
target: 'ws://localhost:4000',
pathRewrite: {
'^/ws' : '/', // rewrite path.
'^/removepath' : '' // remove path.
},
changeOrigin: true, // for vhosted sites, changes host header to match to target's host
ws: true, // enable websocket proxy
logLevel: 'debug'
});
app.use(wsProxy);
app.use(
"/api",
proxy("http://localhost:4000/", {
proxyReqOptDecorator(opts) {
opts.headers["x-forwarded-host"] = "http://localhost:4000/";
return opts;
}
})
);
app.post("/logger", (req, res) => {
logger.debug(req.body.data);
res.send({ status: "SUCCESS" });
});
app.listen(PORT, () => {
logger.debug(`Portal listening on ${PORT}`);
});
Related
I'm trying to use websockets in my app but I'm not able to get Socket.io to connect to my server. Whenever I run the code below, I get this error:
Error: listen EADDRINUSE: address already in use :::3000
I've tried looking up some solutions, and I found that there's no other processes running on this port, so the issue has to be within the project. What could I be doing wrong here?
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const { createServer } = require("http");
const httpServer = createServer(app);
const socketIO = require("socket.io")(3000, { cors: { origin: "*" } });
socketIO.on("connection", (socket) => {
console.log("connected");
});
const port = 3000;
const startServer = () => {
httpServer.listen(port);
console.log(`Listening on port ${port} π`);
};
mongoose
.connect(uri)
.then(() => startServer())
.catch((err) => {
console.log(err);
});
If you don't supply socket.io with an http server, it will create one for you. So your code is actually creating two http servers, both trying to listen on the same port which fails with EADDRINUSE.
Instead, pass the httpServer as the first parameter to socket.io instead of a port number:
const socketIO = require("socket.io")(httpServer, { cors: { origin: "*" } });
It's happening because
const startServer = () => {
httpServer.listen(port);
console.log(`Listening on port ${port} π`);
};
here already the address 3000 in use ... so you shouldn't pass the port:3000 into socketIO, better pass the httpServer, like :
const socketIO = require("socket.io") (httpServer, cors: { origin: "*" } });
socketIO.on("connection", (socket) => {
console.log("connected");
});
I'm trying to build a simple peer to peer image sharing demo app using Node.JS and PeerJS.
But when I try to run the app, I get an error ReferenceError: navigator is not defined.
This is a node.js backend app so I don't get why PeerJS is requesting to identify the navigator.
Could you please help me spot the problem?
Thanks in advance!
app.js
const express = require('express');
const fs = require('fs');
const { resolve } = require('path');
const Peer = require('peerjs');
const app = express();
const port = 9500;
const sender = new Peer('sender', {
host: 'localhost',
port: port,
path: '/'
});
const receiver = new Peer('receiver', {
host: 'localhost',
port: port,
path: '/'
});
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.get('/send', (req, res) => {
...
...
let image = readDataset();
const conn = sender.connect('receiver');
conn.on('open',()=> {
conn.send({
photo: image,
});
res.status(200).send("Image sent.");
});
});
app.get('/receive', (req, res) => {
receiver.on('connection', conn => {
conn.on('data', data => {
...
...
res.status(200).send("Image received and saved.");
});
});
});
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
I am trying to make Postman work with React JS using express. I am following a Mern Stack Development tutorial in free code camp. I have Cors extension enabled in my browsers, both in Chrome and in Edge. I keep getting this message in localhost:5000 "Cannot get /" and get this message {"msg":"This is CORS-enabled for an allowed domain."} in localhost:5000/users/add. My code looks something like this:
This is my server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri,{useNewUrlParser: true, useCreateIndex:true, useUnifiedTopology:true});
const connection= mongoose.connection;
connection.once('open', () =>{
console.log("Mongodb database connection established successfully");
})
const exercisesRouter= require('./routes/exercises');
const usersRouter= require('./routes/users');
var allowlist = ['http://localhost:5000']
var corsOptionsDelegate = function (req, callback) {
var corsOptions;
if (allowlist.indexOf(req.header('Origin')) !== -1) {
corsOptions = { origin: true } // reflect (enable) the requested origin in the CORS response
} else {
corsOptions = { origin: false } // disable CORS for this request
}
callback(null, corsOptions) // callback expects two parameters: error and options
}
app.use('./exercises',exercisesRouter);
app.use('./users', usersRouter);
app.get('/users/add', cors(corsOptionsDelegate), function (req, res, next) {
res.json({msg: 'This is CORS-enabled for an allowed domain.'})
})
app.listen(port, ()=>{
console.log(`Server is running on port: ${port}`);
});
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})
cords donβt have anything to do with this
Can you tell me where is yow route for β/β something like this
app.get(β/β, (req,res)=>{
β¦..
});
Yes exactly. You donβt have it. If the route/endPoint is not declared how do use expect them browsers to show you some else
When browssers open yow link at localhost:5000
They make a get request to β/β. So express just tellβem
Can not get β/β
I do not
[HPM] Error occurred while trying to proxy request /api/users/ from localhost:3000 to http://localhost:5000 (ECONNRESET)
I get this error while trying to do axios.post request,
i'm running my app with concurrently (server with express and client side using react) ,
as described here I defined client/src/setupProxy.js file:
const { createProxyMiddleware } = require('http-proxy-middleware');
module.exports = function(app) {
app.use(
'/api',
createProxyMiddleware({
target: 'http://localhost:5000',
changeOrigin: true,
})
);
};
my server.js:
const express = require('express');
const connectDB = require('./config/db');
const app = express();
//connect Database
connectDB();
//Init MiddleWare -allows to get the data from req.body
app.use(express.json());
//Define routes
app.use("/api/users", require("./routes/api/users"));
app.use("/api/auth", require("./routes/api/auth"));
app.use("/api/profile", require("./routes/api/profile"));
app.use("/api/posts", require("./routes/api/posts"));
app.get('/', (req, res) => res.send('API is running'));
//Port - first look for an environment port (when connect to heroku)
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
console.log(`server listening on port: ${PORT}`);
})
and my post request in the client side:
export const register = ({ name, email, password}) => async dispatch => {
const config = {
headers: {
'Content-Type': 'application/json'
}
}
const body = JSON.stringify({name, email, password});
try {
const res = await axios.post('/api/users/', body, config);
console.log({res});
dispatch({
type: REGISTER_SUCCESS,
payload: res.data
})
console.log('passed dispatch')
} catch (e) {
const errors = e.response.data.errors;
if(errors) {
errors.forEach(e => dispatch(setAlert(e.msg, 'danger')));
}
dispatch({
type: REGISTER_FAIL
})
}
}
any idea what I miss ?
EDIT:
I've noticed that my server using type ipv6 and client on ipv4, maybe that's the problem ? how I make them run on the same ipv ?
I am using Groovy script to perform HTTP POST request with some data:
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.ContentType.*
import groovyx.net.http.ContentType
import static groovyx.net.http.Method.*
def http = new HTTPBuilder('myhost.com')
http.request( POST ) {
uri.path = '/'
requestContentType = ContentType.JSON
body = [title: 'some data', desc: 'some more data']
log.info(body.title)
response.success = { resp,reader ->
log.info( "POST response status: "+resp.statusLine+"}")
}
}
This works just fine, Groovy results are below:
Logs:
INFO : some data
INFO : POST response status: HTTP/1.1 200 OK}
But when I see my web service logs the request body is undefined:
Here's the code:
const express = require('express');
const app = express();
var test = {0:'post'};
app.get('/', (req, res) => {
res.send('a');
console.log('request inbound');
});
app.post('/',(req,res) => {
res.send('test');
console.log('post in');
console.log(req.body);
});
// Listen to the App Engine-specified port, or 8080 otherwise
const PORT = process.env.PORT || 30000;
app.listen(PORT, () => {
console.log(`Server listening on port ${PORT}...`);
});
I'm using Node.js v12.13 | npm v6.12 | express.js 4.17.1
I'm afraid you've omitted app.use(express.json()).
const express = require('express');
const app = express();
app.use(express.json())
var test = {0:'post'};
app.get('/', (req, res) => {
res.send('a');
console.log('request inbound');
});
...