I'm trying to deploy my Express API in my EC2. But I keep getting this error "ERR_SSL_PROTOCOL_ERROR" and despite my researches, I cannot find the right thing to do to fix my error.
My front end is on apache and requesting information through PUT/GET request toward the API. I've open the port on AWS and updated default-ssl.conf apache's file :
const express = require('express')
const axios = require('axios');
var cors = require('cors')
const app = express();
const fs = require('fs');
const bodyParser = require('body-parser');
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const execSync = require('child_process').execSync;
app.use(cors())// Authorize navigator calls
app.use(bodyParser.urlencoded({ extended: true }));
// We send the rarity table
app.get("/rarity", async (req, res) => {
try {
let nft_json = JSON.parse(fs.readFileSync('rarity.json', 'utf-8'));
// We gather the information regarding this NFT to mint it
console.log(nft_json);
res.send(nft_json);
}
catch (err) {
console.log("error rarity table")
}
})
app.listen(8080, () => {
console.log("Serveur à l'écoute")
})
ServerName www.xx.com
SSLEngine on
ProxyPass /rarity https://www.xx.com:8080
ProxyPassReverse /rarity https://www.xx.com:8080
I can access the express /rarity through http but not https. What am I doing wrong in my default-ssl.conf ?
Have a great day,
regards
Related
Cookies are not set in browser. I am use the node as backend. I am try to search problem some person tell that's cookies will not setting because of I am using react as front and node as backed both are run on same virtual server that is localhost. That why it happen.
this is my code please help.
User.js
const bcrypt = require('bcrypt');
const jwt = require('jsonwebtoken');
const RegisterModel = require("../Model/RegisterModel")
const signIn = async (req,res)=>{
try {
const data = await RegisterModel.findOne({Email:req.body.email})
const passwordMatch = await bcrypt.compare(req.body.password,data.Password)
const token = await jwt.sign({Email : data.Email}, process.env.SECRET)
if(!data) return res.status(404).json({islogin:false, message: "User doesn't exist" })
if(!passwordMatch) return res.status(400).json({islogin:false,message: "Incorrect Password"})
if(passwordMatch){
res.cookie('newToken',token, { maxAge: 900000, httpOnly: false});
res.status(200).send({id:data._id,email:data.Email,name:data.Name,islogin:true,token:token})
}
} catch (error) {
res.status(404).json({islogin:false,message:"User doesn't exist"})
console.log(error)
}
}
module.exports = {signIn,signUp};
app.js
const express = require('express');
var cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser())
const dotenv = require('dotenv');
dotenv.config()
var cors = require('cors')
const PORT = process.env.PORT ;
const router = require("./Router/Router")
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended:false}));
app.use(router);
require("./Connection/Connection")
app.listen(PORT,()=>{
console.log(`Listen at Port ${PORT}` )
})
for set credentials data into browser it is necessary to run both side on same domain backend should be run on localhost or 127.0.0.1 and frontend should be run on localhost or 127.0.0.1 respectively.
or
backend and frontend run on =localhost or
backend and frontend run on =127.0.0.1
if you are not sure then issue error's show on console. here
browser suggest you error regarding cookies.
also set cors policy on backend side like =
cors({origin:"http:localhost:frontendPORT", credentials:true})
frontend side on http request, must be set with credentials= true
this method work for me after spending 4 days.
I have written a simple request response code in NODEJS but there is no response in return of the request is there .
The code for my app.js(Server file) is
const express = require('express');
const cors = require('cors')
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors);
app.use("/api",paymentroute);
app.listen(3100,()=>{
console.log(`listening to port 3100`);
})
The code for my req and res is
const express = require('express');
const router = express.Router();
// const { checkout } = require('../controllers/paymentController');
router.post("/checkout",(req,res) => {
console.log("this function is called ")
return res.json({success:"true"})
});
module.exports = router;
Even the console.log inside the res function is not working.
Just change app.use(cors); to app.use(cors());
const express = require('express');
const cors = require('cors');
const paymentroute = require('./routes/paymentRoutes');
const app = express();
app.use(cors());
app.use('/api', paymentroute);
app.listen(3100, () => {
console.log(`listening to port 3100`);
});
I think it is a connection-related issue often related to a networking issue caused by a Virtual Private Network (VPN) that in some cases is required by some API services or, in other cases, prevents you to reach an API service.
The issue seems to be a combo of having the no-cache header enabled and a request URL length over 64 characters. If the issue persists after doing this solution then try to upgrade to the latest version of Postman.
Hey, I built ssl communication with self certificate. The connection is working, but when I trying to deliver data on the client side with post request in postman or my android client, the body of the request in the server side is empty.
Here is my nodejs server code below,thankes for help.
const express = require('express')
const https = require('https')
const path = require('path')
const fs = require('fs')
const app = express()
app.use(express.json())
app.post('/',(req,res,next)=>
{
console.log("we got new connection")
var data =req.body
res.send(data)
})
const ssl_server = https.createServer(
{
key:fs.readFileSync(path.join(__dirname,'cert','key.pem')),
cert:fs.readFileSync(path.join(__dirname,'cert','cert.pem'))
},app)
ssl_server.listen(3443,console.log("SSl server is online!"))
You're reading the response body. You should look at the request.
In any case, there won't probably be much reasonable data to read unless you parse the POST payload somehow; I'd recommend the Express library rather than raw Node.js HTTP bits if you don't want to do that yourself.
here is my answer for my question,like AKS said, you need to parse the post request, i add bodyparser to my code and it worked.
const express = require('express')
const https = require('https')
const path = require('path')
const fs = require('fs')
const bodyParser = require('body-parser');
const app = express()
app.use(bodyParser.urlencoded({ extended: true })) // <==== parse request body as JSON
app.post('/',(req,res,next)=>
{
console.log("we got new connection")
var data =req.body
res.send(data)
})
const ssl_server = https.createServer(
{
key:fs.readFileSync(path.join(__dirname,'cert','key.pem')),
cert:fs.readFileSync(path.join(__dirname,'cert','cert.pem'))
},app)
ssl_server.listen(3443,console.log("SSl server is online!"))
I am trying to start my project via launching server.js but I am getting error:"cannot GET /"
even after I made an app.get() route in my server.js
I am using also "body-parser" as a middleware, and "cors"
server.js:
// Setup empty JS object to act as endpoint for all routes
const projectData = {};
// Require Express to run server and routes
const express = require('express');
// Start up an instance of app
const app = express();
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());
// Initialize the main project folder
app.use(express.static('views'));
const port = 8080;
app.use(express.static('dist'));
// Setup Server
const server=app.listen(port, ()=>{console.log(`running on localhost: ${port}`)});
app.get('/all', sendData);
function sendData (request, response) {
response.send(projectData);
};
// TODO-ROUTES!
app.post('/add', Info);
function Info(req, res) {
projectData['date'] = req.body.date;
projectData['temp'] = req.body.temp;
projectData['content'] = req.body.content;
res.send(projectData);
}
module.exports = server;
I made a POST request to /add and it works. Then I call GET /all and also work. The error cannot GET / is because you are requesting an endpoint that not exists.
Just add a dummy data to your Fn() if you want to see some output on GET request wihtout making any post request
Here is my solution
app.get('/', (req, res) => {
res.redirect('/all');
})
we need this because you do not have any root URL set, so we set the root URL to redirect to /all
2nd step then we add a dummy data in the projectData
var projectData = {
date = new Date().getDate();,
temp = 10,
content="This is Test Content"
}
This way when you call 'http://localhost:8080/' you shall get redirected to http://localhost:8080/all and instead of empty {} you shall see the dummy data.
Due to my shared-hosting situation, I was forced to have all incoming requests redirected to a non-80 port on localhost, which I did through htaccess. This mutates the HTTP host header to always say localhost, no matter what subdomain I try to request. Simple enough, I found a workaround to use x-forwarded-host instead, but this means that I'm not able to rely on any of the Express subdomain middleware packages currently available on NPM, as they all rely on that host header (as far as I'm aware).
So I managed to send requests to the router. But for some reason, any request handling I try to do with the router for the specific subdomain that I have activated, won't get picked up by the router, and passes straight on through to the 404 handler.
/index.js:
const path = require('path');
const fs = require('fs');
const express = require('express');
const app = express();
const PORT = 30001;
const subdomainHosts = [];
fs.readdirSync('./routes/subdomain').filter(file => file.endsWith('.js')).forEach(host => {
subdomainHosts.push(host.split('.js')[0]);
});
const forwardSubdomain = require('./middlewares/forwardSubdomain');
app.use(forwardSubdomain(subdomainHosts));
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
return res.status(404).sendFile(path.join(process.cwd(), 'public/404.html'));
});
/middlewares/forwardSubdomain.js:
module.exports = (subdomainHosts) => {
return (req, res, next) => {
let host = req.headers['x-forwarded-host'] ? req.headers['x-forwarded-host'] : '';
host = host.split(':')[0].split('.example.com')[0];
const isSubdomain = (host && subdomainHosts.includes(host));
if (isSubdomain) {
const subdomainRouter = require(`../routes/subdomain/${host}.js`);
return subdomainRouter(req, res, next);
}
next();
};
};
/routes/subdomain/test.js:
const path = require('path');
const express = require('express');
const router = express.Router();
router.use(express.static(path.join(process.cwd(), 'test')));
module.exports = router;
/test/ contains a simple hello world index.html. Yet, trying to access test.example.com gives me the 404.
I'm pretty certain that I'm missing something obvious, but I've been sitting on this for a bit too long, hence the cry for help.