FE in react set up with create-react-app
BE in node
I deployed the app on heroku and all looks good but when I do a get to my BE I get a 404 (Not Found).
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var serveStatic = require('serve-static');
app = express();
app.use(bodyParser());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
var port = process.env.PORT || 5000;
require('./server/routes')(app);
app.listen(port);
console.log('server started '+ port);
this is the route
module.exports = function (app) {
let apiUrlBase = "/api/v1";
app.get(`${apiUrlBase}/get-report/:_email`, (req, res) => {
const email = req.params._email;
axios.get(`https://www.beenverified.com/hk/dd/email?email=${email}`)
.then(response => {
let parserNames = utils.getNames(response.data);
let parserEmails = utils.getEmails(response.data);
let parserJobs = utils.getJobs(response.data);
let parserSocials = utils.getSocials(response.data);
let report = { "names": parserNames, "emails": parserEmails, "jobs": parserJobs, "socials": parserSocials };
res.json(report);
})
.catch(error => {
res.status(500).send('Internal Server Error');
});
})
}
Make sure your express app distinguishes both your api endpoint and your react app endpoint if you are serving both the api and the react app in one express instance. I ran into a similar problem. See Redux-Saga with babel/webpack "actions must be plain objects..." error in production but not dev
Related
i have a chat app built with laravel and socket.io. My laravel app is located on one domain while my nodejs app is on another domain. Connecting to my nodejs signalling app gives a cors error while the nodejs app also returns cors error. Here is my nodejs app
"use strict";
require('dotenv').config();
const express = require('express');
const app = express();
const fs = require('fs');
const options = {
key: fs.readFileSync(process.env.KEY_PATH),
cert: fs.readFileSync(process.env.CERT_PATH)
};
const https = require('https').Server(options, app);
const io = require('socket.io')(https);
io.origins('*:*');
const listner = https.listen(process.env.PORT, function() {
console.log('Listening on ', listner.address().port);
});
//allow only the specified domain to connect
io.set('origins', process.env.DOMAIN + ':*');
require('./socket')(io);
app.get('/', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
// Add this
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, OPTIONS');
res.header('Access-Control-Max-Age', 120);
return res.status(200).json({});
}
res.send('Ok');
next();
I have installed a cors middleware on my laravel backend but no difference whatsover. Any help will be appreciated
You need to remove these two line. cos, you have first set for any origin and the you have specified domain with env.
io.origins('*:*');
io.set('origins', process.env.DOMAIN + ':*');
Exact way to allow user is
// process.env.DOMAIN == "https://anydomain.com:port"
// process.env.DOMAIN != "anydomain.com:port"
const options={
cors:true,
origins:[process.env.DOMAIN],
}
const io = require('socket.io')(https, options);
I've been working on chat functionality. There are two kinds of clients, One is the frontend of my application and the second is random another website.
I know there are plenty of issues like this but I tried all of the solution but I'm still getting following error:
Access to XMLHttpRequest at 'https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjoM1w' from origin 'null' has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
and this the error I'm getting on client-side of my own front end:
https://mydomain/socket.io/?EIO=3&transport=polling&t=NCjnJUX 404 (Not Found)
This is how I'm trying to connect from client-side.
var socket = io.connect("https://mydomain:443/", {secure: true, port: '443'});
and this is my server.js code
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const passport = require("passport");
const users = require("./routes/api/users");
const base = require("./routes/api/base");
const leads = require("./routes/api/leads");
const requests = require("./routes/api/requests");
const offApp = require("./routes/api/offApp");
const chat = require("./routes/api/chat");
const chatSocket = require("./routes/socket/chat");
const path = require("path"); // on top
const app = express();
// const client = require('socket.io').listen(4000).sockets;
const https = require('https');
const fs = require('fs');
var options = {
pfx: fs.readFileSync('certificate.pfx'),
passphrase: 'password'
};
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, *');
next();
});
var server = https.createServer(options, app);
var client = require("socket.io").listen(server);
client.origins('*:*') ;
server.listen(443);
// Bodyparser middleware
app.use(
bodyParser.urlencoded({
extended: false
})
);
app.use(bodyParser.json());
// DB Config
const db = require("./config/keys").mongoURI;
// Connect to MongoDB
mongoose
.connect(
db,
{ useNewUrlParser: true }, (err, db) => {
if (err) {
throw err;
}
console.log('MongoDB connected');
chatSocket(db, client);
});
// Passport middleware
app.use(passport.initialize());
// Passport config
require("./config/passport")(passport);
// Routes
app.use("/api/users", users);
app.use("/api/base", base);
app.use("/api/leads", leads);
app.use("/api/requests", requests);
app.use("/api/offapp", offApp);
app.use("/api/chat", chat);
const port = process.env.PORT || 5000;
app.use(express.static("client/build")); // change this if your dir structure is different
app.get("*", (req, res) => {
res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});
app.listen(port, () => console.log(`Server up and running on port ${port} !`));
Please help me resolve this CORS and other issues. I am using the Azure app service. That's why I can't use any other port than 80 and 433
Install cors package using npm i cors
In your app.js file,
const cors = require('cors')
app.use(cors());
// use CORS like that-
// you need to use it as middle ware
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
Danish try this solution, I hope it will work
const client = require("socket.io")(server, {
handlePreflightRequest: (req, res) => {
const headers = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
"Access-Control-Allow-Origin": req.headers.origin, //or the specific origin you want to give access to,
"Access-Control-Allow-Credentials": true
};
res.writeHead(200, headers);
res.end();
}
});
client.on("connection", () => {
console.log("Connected!");
});
server.listen(443);
I've been banging my head against the wall on this one for a few hours. I'm not sure why it doesn't work but it's probably something simple I'm missing. It usually is...
Anyway, I'm doing a simple HTTP PUT from Angular 7 like this:
protected put(cmd: string, body: any) {
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
console.log(body);
return this._http.put(cmd, body, {headers: headers});
}
cmd and body are being passed in. I can see the body print out in the console and the cmd path is correct to hit my route path in Node.
From there, it comes into my Node/Express app. Which goes as follows:
'use strict';
const express = require('express');
const bodyParser = require('body-parser')
// Constants
const PORT = 8080;
const HOST = '0.0.0.0';
// App
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-
Type, Accept");
next();
});
app.use('/api', require('./routes/routes'));
app.use('/api/add-user', require('./routes/add-user/routes'));
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
And this is my routes file that console prints the empty body:
const express = require('express');
const router = express.Router();
const dvAdmin = require('../../controller/controller');
//Routes
//GETS
//PUTS
router.put('/addCCUser', function (req, res) {
console.log(req.body);
});
module.exports = router;
I am creating a REST api using Node.js And Express, The application works fine including routes and other functanalities on local computer but when uploaded to windows server routes are not working properly, I was able to see Hello World printed on my from home page e.g:- www.abcd.com/,
But when routes are being used eg:- www.abcd.com/users/ it gives 404 - File or directory not found.
Here is my code
server.js
const http = require('http')
const app = require('./app')
const server = http.createServer(app);
server.listen(process.env.PORT, () => {
console.log("Server Started");
});
app.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const app = express();
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header(
'Access-Control-Allow-Origin',
'*'
);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-with, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
const users_routes = require('./api/routes/users.routes');
const message_routes = require('./api/routes/message.routes');
const group_routes = require('./api/routes/group.routes');
const key_routes = require('./api/routes/key.routes');
console.log(users_routes.toString());
app.use('users', users_routes);
app.use('message', message_routes);
app.use('group', group_routes);
app.use('key', key_routes);
app.use('/', (req, res, next) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<H1>Hello World!</H1>');
});
module.exports = app;
user.routes.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
Console.log("Hello there");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<H1>Hello World!</H1>');
});
module.exports = router;
Log file after starting app
Server Started
It prints function when used typeof(user_routes)
My app.js
const express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
path = require('path'),
mongoose = require('mongoose'),
app = express(),
config = require('./config'),
Note = require('./models/note'),
server = require('http').createServer(app),
io = require('socket.io')(server),
socket = io.socket;
mongoose.connect('mongodb://'+config.db.host+'/'+config.db.name);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Serve static assets
app.use(express.static(path.resolve(__dirname, '..', 'build')));
app.use(function(req, res, next) {
const allowedOrigins = [
'http://127.0.0.1:8000',
'http://localhost:8000',
'http://127.0.0.1:3000',
'http://localhost:3000'];
const origin = req.headers.origin;
if(allowedOrigins.indexOf(origin) > -1){
res.setHeader('Access-Control-Allow-Origin', origin);
}
//res.header("Access-Control-Allow-Origin", "127.0.0.1 localhost");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Credentials', true);
next();
});
calling socket.emit() in handlers after above codes.
My index.js
'use strict';
const app = require('./app'),
// server = http.createServer(app),
PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
console.log(`REST API running on ${PORT}!`);
});
Console output:
Any idea? Thanks
If you're going to do this:
server = require('http').createServer(app),
Then, you can't do:
app.listen(PORT, ...);
because app.listen() will create a new and different server and socket.io will not be associated with that one.
Instead, you need to do:
server.listen(PORT, ...)
using the server value from app.js. And, if you want to require() in the server from app.js, you also need to export it from app.js (something else I don't see your code doing).
For reference, the code for app.listen(), does this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
You can see how it creates a different server than the one you passed to socket.io. Thus the one you passed to socket.io is never started and thus socket.io does not work.