I have deployed a react-app to AWS S3 and a node/express API in heroku but Iam not able to connect them together event with the cors config in the API or proxy in the react-app
I can't find to make this correct.
frontend package.json
"name": "frontend",
"proxy": "https://planet-api-test.herokuapp.com/",
"version": "0.1.0",
"private": true,
app.js
const [message, setMessage] = useState('')
useEffect(() => {
const myFunction = async () => {
const { data } = await axios.get('/api/users')
setMessage(data)
}
myFunction()
})
server.js
import express from 'express'
import cors from 'cors'
import userRoutes from './routes/userRoutes.js'
const app = express()
const port = process.env.PORT || 5000
app.use(express.json())
app.use(cors())
app.use('/api/users', userRoutes)
error in console
for some reason your app tries to send the request to http instead of https try to hard-code it inside the axios.get see what happens
Related
I am making a web app and have made back-end with express, mongodb and node.js, while the frontend is made in React.js.
The backend runs completely fine on its own, when run using "nodemon server.js"
But when connected to frontend using axios, it throws "Network Error" error.
Here is my code to server.js (back-end, connecting url) and http-common.js (front-end, axios)
server.js
import cors from "cors";
import userquery from "./student/api/query.routes.js";
import admin from "./admin/api/admin.routes.js";
const app = express();
app.use(cors());
app.use(express.json());
app.use("/api/v1/user", userquery);
app.use("/api/v1/admin", admin);
app.use("*", (req, res) => {
res.status(404).json({ error: "not found" });
});
export default app;
query.routes.js
import QueryCtrl from "./query.controller.js";
import personalQueriesCtrl from "./personalQueries.controller.js";
import SubjectCtrl from "./subject.controller.js";
import UserCtrl from "./user.controller.js";
const router = express.Router(); //creates routes people can go to
router.route("/").get(QueryCtrl.apiGetQueries);
router.route("/signup").post(UserCtrl.apiPostUser);
router.route("/subjects").get(SubjectCtrl.apiGetSubjects);
router.route("/AskQuery").post(personalQueriesCtrl.apiPostQuery);
export default router;
http-common.js
export default axios.create({
baseURL: "http://localhost:5000/api/v1/user/",
headers: {
"Content-type": "application/json",
},
proxy: false,
});
Please help if you can!
There are 3 file created in /config.
default.json
{
"host": "localhost",
"port": "PORT",
"msg": "default"
}
local.json
{
"host": "localhost",
"port": 3030,
"msg": "local"
}
dev.json
{
"host": "localhost",
"port": 3030,
"msg": "dev"
}
Whenever the application runs, it should log something like info: Feathers application started on http://localhost:3030 in dev, which "dev" is the msg variable in config file.
index.js
/* eslint-disable no-console */
const logger = require('./logger');
const app = require('./app');
const port = app.get('port');
const msg = app.get('msg');
const server = app.listen(port);
process.on('unhandledRejection', (reason, p) =>
logger.error('Unhandled Rejection at: Promise ', p, reason)
);
server.on('listening', () =>
logger.info('Feathers application started on http://%s:%d in %s', app.get('host'), port, msg)
);
I tried to set NODE_ENV=dev, but every time I run the application by nodemon --legacy-watch ./src, it shows:
info: Feathers application started on http://localhost:3030 in local
but I am expecting
info: Feathers application started on http://localhost:3030 in dev
I tried to log process.env.NODE_ENV, but it shows dev correctly
app.js
const path = require('path');
const favicon = require('serve-favicon');
const compress = require('compression');
const helmet = require('helmet');
const cors = require('cors');
const logger = require('./logger');
const feathers = require('#feathersjs/feathers');
process.env['NODE_CONFIG_DIR'] = 'config/'. // I tried to add this according to doc but still not working
const configuration = require('#feathersjs/configuration');
const express = require('#feathersjs/express');
const socketio = require('#feathersjs/socketio');
const middleware = require('./middleware');
const services = require('./services');
const appHooks = require('./app.hooks');
const channels = require('./channels');
const authentication = require('./authentication');
const sequelize = require('./sequelize');
const app = express(feathers());
// Load app configuration
app.configure(configuration());
console.log(app.settings.msg); //<--------------------------------- show "local"
console.log(process.env.NODE_ENV); // <---------------------------- show "dev"
// Enable security, CORS, compression, favicon and body parsing
app.use(helmet({
contentSecurityPolicy: false
}));
app.use(cors());
app.use(compress());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
app.use(favicon(path.join(app.get('public'), 'favicon.ico')));
// Host the public folder
app.use('/', express.static(app.get('public')));
// Set up Plugins and providers
app.configure(express.rest());
app.configure(socketio());
app.configure(sequelize);
// Configure other middleware (see `middleware/index.js`)
app.configure(middleware);
app.configure(authentication);
// Set up our services (see `services/index.js`)
app.configure(services);
// Set up event channels (see channels.js)
app.configure(channels);
// Configure a middleware for 404s and the error handler
app.use(express.notFound());
app.use(express.errorHandler({ logger }));
app.hooks(appHooks);
module.exports = app;
Update
After I remove local.json, it works perfectly but it doesn't makes sense?
I am trying to configure redirect-ssl node module into nuxt application
Referece : https://www.npmjs.com/package/redirect-ssl
But when i load site in browser it gives me error with message -> Cannot GET /
ref. https://prnt.sc/xqsc05
Site works on SSL without redirect module. But I want to forcefully redirect all non HTTP request to HTTPS. I tried .htaccess code but I think nuxt do not supports it.
There is no error into terminal.
Tried following into nuxt.config.js different ways as following.
serverMiddleware: ["redirect-ssl"],
Into server/index.js file added following code
const redirectSSL = require('redirect-ssl')
async function start () {
.
.
app.use(redirectSSL)
}
How can we use .htaccess file into nuxt. I tried placing into root or nuxt project setup, but that did not worked for me.
Also anyone know how to implement CDN into nuxt other than build:publicPath variable.
Any help or suggestion for redirect-ssl module or nuxt with htaccess please ?
Try out following way.
Into server/index.js
const redirectSSL = require('redirect-ssl');
const fs = require("fs");
const path = require("path");
const https = require('https');
const express = require('express');
const consola = require('consola');
const { Nuxt, Builder } = require('nuxt');
const app = express()
const pkey = fs.readFileSync(path.resolve(__dirname, 'domain_ssl.com.key'));
const pcert = fs.readFileSync(path.resolve(__dirname, 'domain_ssl.com.crt'));
const httpsOptions = {
key: pkey,
cert: pcert
};
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = false
async function start () {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
await nuxt.ready()
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// nuxt render and middleware
app.use(nuxt.render)
app.use(redirectSSL.create({ redirectPort: 443 }))
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
https.createServer(httpsOptions,app).listen(443, host)
consola.ready({
message: `Server listening on https://${host}:${port}`,
badge: true
})
}
start()
Above one is for forcefully SSL redirection. And for CDN use this steps.
https://nuxtjs.org/docs/2.x/configuration-glossary/configuration-build
We are using CORS to allow all origins
app.use(cors());
server running on port 4000, and client running on 3000
here is my server.js code
const cors = require("cors");
const http = require("http");
const socketIO = require("socket.io");
app.use(cors());
const port = process.env.PORT || process.env.DEFAULT_PORT;
console.log("port: ", port);
app.listen(port, () => {
console.log(`App listening at ${port}...`);
});
const server = http.createServer(app);
const io = new socketIO(server, {
transports: ["websocket"],
});
React js code
constructor(props) {
super(props);
try {
this.socket = io("http://localhost:4000", { transport: ["websocket"] });
this.socket.on("Chat-event", data => {
console.log("socketdata", data);
});
} catch (error) {
console.log("hiterror", error)
}
}
I am continuously getting this error on the client side after allowing origin for all.
Access to XMLHttpRequest at 'http://localhost:4000/socket.io/?EIO=3&transport=polling&t=Mv-SSIc' from origin 'http://localhost:3000' 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
For socket.io version 3.x.x cors configuration has changed, I managed to fix it by adding options to the socket creation.
Tried on the version 2.x.x also and it worked.
const io = socketio(httpServer, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
}
});
Here is the resource https://socket.io/docs/v3/handling-cors/
Bonus: In case you encounter Bad Request make sure you have the same version of socket.io for the client and the server.
By following these steps you can get rid of these error.
// 1) on server side
const cors = require('cors');
const socketio = require('socket.io')
const http = require('http');
const server = http.createServer(app);
const io = socketio(server, {
cors: {
origin: localhost:3000/, //your website origin
methods: ["GET", "POST"],
credentials: true
}
});
// 2) add these middlewares
app.use(cors())
app.options('*', cors());
// 3) on client-side
import io from 'socket.io-client'
let socket = io.connect(localhost:8080, { transports: ['websocket'] }) // your local server
try using the cors credentials config:
app.use(cors({credentials: true}));
Please allow all to socket.io at server side
const socketIO = require('socket.io')(server, { origins: '*:*'});
Or you can set socketIO origins as *
socketIO.set('origins', '*:*');
#user4860402 Gave me solution, thing is that by default npm is installing socket.io client v 2.X.X but on server I'm using latest verion (also provided by npm) 3.0.5
So all problems including 400 error comes because client and server verion doesnot match.
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const socketio = require("socket.io");
const cors = require("cors");
const io = socketio(http, {cors:{origin:"*"}});
Been working fine up until this morning and now, suddenly i am getting a type error stating that Cors is not a function
My code
import * as Cors from "cors";
...
const corsOptions: Cors.CorsOptions = {
allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Accept", "X-Access-Token", "Authorization"],
credentials: true,
methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
origin: "*",
preflightContinue: true
};
createConnection(ormConfig).then(async connection => {
// run pending migrations
await connection.runMigrations();
// create express server
const app = express();
app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true}));
// register cors
app.use(Cors(corsOptions)); //<---error occurs here
// register all controllers
useExpressServer(app, {
routePrefix: "/api",
controllers: [
__dirname + "/controllers/**/*{.js,.ts}"
],
authorizationChecker: async (action: any, roles: string[]) => {
return JwtAuthorizationMiddleware.checkIsAuthorized(action, roles);
},
currentUserChecker: async (actions: any) => {
return JwtAuthorizationMiddleware.extractUserFromJwtToken(actions);
}
});
// start the express server
const port: number = +(process.env.PORT || 44320);
app.listen(port, (err: Error) => {
console.log(`App listening on port ${port}`);
console.log("Press Ctrl+C to quit.");
});
}).catch(error => console.error("TypeORM connection error: ", error));
Current versions of cors and Node
cors: "^2.8.4"
Node: v8.4.0
The only change that recently done was on Friday when I included the following packages
multer: "^1.3.0"
#google-cloud/datastore: "^1.1.0"
#google-cloud/storage: "^1.4.0"
and everything was working till this morning, same version is deployed on gcloud and this works so I am a little bemused as to why I Am suddenly getting this error and what could be the cause.
Any help is greatly appreciated
You have to have something such as
const cors = require('cors');
in the top of your file, and then refer to the module as cors, not Cors.
You can read Express's cors documentation to learn more.
To apply cors to all routes in your project you can write:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
Ok, so I found the problem which turned out to be PEBKAC.
While implementing file uploads and storage in gcloud, I had to enable CORS on gcloud and had saved the settings file in the root of my project, this file was called cors.json.
In the code posted in my question above the import statement was reading my cors.json file and not (as I thought) the cors NPM package.
Lesson learnt from this one should anyone else make the same rookie mistake I just made is be careful what you name your files and where you put them!!!