I am trying to display a dicom with NODEJS but the browser throws me this problem
XMLHttpRequest can not load http: // localhost: 8080 / wado?
RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 &
contentType = application% 2Fdicom & transferSyntax =
1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is
therefore not allowed access.
Then install npm the package cors
And here I leave my code part of my code app.js
Var express = require ('express');
Var cors = require ('cors')
App.use (cors ())
App.listen (3000, function () {
Console.log ('listening on 3000')
})
Also try adding this in app.js
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 ();
});
But the browser still displays the error:
XMLHttpRequest can not load http: // localhost: 8080 / wado?
RequestType = WADO & studyUID = 1.2.840.113704.1.111.5 ... 26513.429 &
contentType = application% 2Fdicom & transferSyntax =
1.2.840.10008.1.2. In 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http: // localhost: 3000' is
therefore not allowed access.
I have doubt because I also use the route index.js which I leave here
var express = require('express');
var router = express.Router();
var cors = require('cors')
/*var express = require('express');
var router = express.Router();*/
var mysql = require('mysql');
router.use(cors({origin: 'http://localhost:3000'}));
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
I'm sorry for my English
For security purpose browsers don't allow cross origin requests under normal conditions.
Your page is loading from localhost:3000, which defines the origin as it is the first request. Your code is trying to load data from another service running on port- 8080, that is different from origin. So basically you need to enable cors on the service running on port 8080 as it is the external source.
Related
I am facing an issue with REST APIs. My front-end is in React and APIs are in Express. I intermittently get below error. I've gone through many other similar posts and tried to add HTTP headers to the response without any luck. These calls works fine from Postman client.
"from origin 'http://localhost:3000' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested
resource."
So, far I've added below lines to populate HTTP response. The MOST annoying part is these errors only happens with certain web services and not others. They all are identically coded so, it makes it difficult to determine why in certain cases it fails.
My server.js (Express REST app) is as per below ...
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
const controllers = require('./controllers');
const logger = require('./logger/logger');
const port = 9000;
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json());
app.use(bodyParser.raw());
controllers.init(app);
app.use(cors());
//Listen server on define port
var server = app.listen(port, () => {
logger.info("API Server is running on port " + port);
})
So, far what I've noticed is, when I add the below segment to include HTTP response headers in my controllers (controllers uses services and models to serve requests), the error disappears EVEN if I remove them after first successful call from my React front-end and this is really bizarre. I use Chrome to test my React front-end. Does this mean Chrome browser is caching something esp. when it comes to the origin? I am worried how this will span out in production? has anyone experienced this sort of behaviour?
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', "*");
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
Below are the packages I use for the Express API server ..My React front-end uses "react": "^16.13.1"
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
ok, just managed to get this work by adding the below segment
controllers.init = function (app) {
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', '*');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
in my index.js under controllers folder. index.js contains init for all other controllers....see below
(function (controllers) {
var appMenuController = require("./appMenuController");
var applicantTypeController = require("./applicantTypeController");
var permitApplicationController = require("./permitApplicationController");
var campusController = require("./campusController");
var paymentMethodController = require("./paymentMethodController");
var permitTypeController = require("./permitTypeController");
var permitController = require("./permitController");
var permitChangeRequestController = require("./permitChangeRequestController");
var requestTypeController = require("./requestTypeController");
var vehicleController = require("./vehicleController");
controllers.init = function (app) {
app.use((req, res, next) => {
res.append('Access-Control-Allow-Origin', '*');
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
appMenuController.init(app);
applicantTypeController.init(app);
permitApplicationController.init(app);
campusController.init(app);
paymentMethodController.init(app);
permitTypeController.init(app);
permitController.init(app);
permitChangeRequestController.init(app);
requestTypeController.init(app);
vehicleController.init(app)
}
})(module.exports);
I still don't get it i.e. why Chrome (even Firefox) won't allow HTTP REQ\RESP comms between 2 localhosts on the same host i.e. localhost. Where is a threat in responses originating from the localhost? unless I misunderstood CORS
We are facing CORS issue in Angular 6 using socket.io client when we are trying to connect to the server.
The error we are getting in the console of browser.
Access to XMLHttpRequest at 'http://********.com/socket.io/?EIO=3&transport=polling&t=N3jTiAZ' from origin 'http://localhost:4200' 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.
Here is the server code
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const server = require('http').createServer(app);
const conn = app.listen("3000")
const io = require('socket.io').listen(conn);
io.origins('*:*')
var connectioncheck = io.of('/check-connection');
connectioncheck.on('connection', function (socket) {
console.log('user connected');
});
Here is frontend code using simple html and js
<script src="https://cdn.jsdelivr.net/npm/socket.io-client#2/dist/socket.io.js"></script>
var socket = io.connect('http://********.com/check-connection');
socket.emit('connection', "hello",function(db){
console.log(db);
console.log("data from callback");
});
According to comments you gave above I think you should use NPM CORS in a way like this
let allowedOrigins = ["http://ServerA:3000", "http://ServerB:3000"]
let origin = req.headers.origin;
if (allowedOrigins.includes(origin)) {
res.header("Access-Control-Allow-Origin", origin); // restrict it to the required domain
}
I’m using the MEAN stack (MongoDB, Express, Angular, and NodeJS).
There is a simple function to get data from an external API like this:
let api = 'https://thongtindoanhnghiep.co/api/city';
return this.http.get<any>(api).subscribe(res => { this.data = res; });
But whenever it sends a request, I get the following error:
"OPTIONS https://thongtindoanhnghiep.co/api/city 405 (Method Not Allowed)
Access to XMLHttpRequest at 'https://thongtindoanhnghiep.co/api/city' from origin 'http://localhost:4040' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status."
My Chrome has web security disabled, with the CORS extension installed, and my app is configured to enable CORS on the server side.
When I use Postman to do this, it is working well.
In node js you have fix this issue in 2 type
Type 1
install cors
npm install cors
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
// cors config
app.use(function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT,DELETE");
res.header("Access-Control-Allow-Headers", "*");
next();
});
app.listen(8083, () => {
console.log('Server connected with 8083');
})
Type 2
npm install browser-sync --save
var fs = require('fs');
var http = require('http');
var https = require('https');
var privateKey = fs.readFileSync('node_modules/browser-sync/certs/server.key', 'utf8');
var certificate = fs.readFileSync('node_modules/browser-sync/certs/server.crt', 'utf8');
var credentials = {key: privateKey, cert: certificate};
var httpServer = http.createServer(app);
var httpsServer = https.createServer(credentials, app);
httpServer.listen(8080,()=>{
console.log('Server connected with 8080');
});
httpsServer.listen(8081,()=>{
console.log('Server connected with 8081');
});
In that way you provide express middleware to the native http/https server
If you want your app running on ports below 1024, you will need to use sudo command (not recommended) or use a reverse proxy (e.g. nginx, haproxy).
You can use this in your Node.js application entry point
var cors = require('cors')
app.use(cors())
Or
You can use response object to set the header
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Hopefully this should solve the problem.
CORS is fine on server and works as intended. I tried sending requests to my server's REST API with the angular HTTPClient and I receive a CORS error.
Why is this an error if CORS is enabled on the server? Shouldn't it be fine on the client?
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/blah/blah (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
How can I enable CORS on this request please.....
For future refrence it was "Davids" answer that assisted me, the cors was not added before all routing.
"..... Meaning, before the route is defined."
so right after ...
var app = express();
I just use...
app.use(cors());
A little intro:
Cross-Origin Resource Sharing aka CORS is a mechanism that uses additional HTTP headers to tell browsers to give a web application running at one origin (e.g. http://localhost:3000), access to selected resources from a different origin (e.g. http://localhost:8080). In other words, a web app executes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, or port) from its own. For security reasons, browsers restrict cross-origin HTTP requests initiated from scripts.
The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS.
How to Fix CORS Issues?
You can do it yourself by creating an Express middleware. Here's the appropriate code snippet:
// Enable CORS for specific origins:
app.use((req, res, next) => {
// Allow multiple predefined origins
const allowedOrigins = ["https://deployed-app.com", "http://localhost:3000"];
const origin = req.headers.origin; // extract the origin from the header
if (allowedOrigins.indexOf(origin) > -1) { // if the origin is present in our array
res.setHeader("Access-Control-Allow-Origin", origin); // set the CORS header on the response
}
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next(); // move on to the next middleware
});
Alternatively, you can accept all requests,
but this option is only appropriate if you're in development or if your API is public :)
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
Additionally, there's an Express CORS middleware and this is how you would use it:
npm install cors --save
Enable All CORS Requests:
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`CORS-enabled server is up on ${port}`);
});
Enable CORS for a Single Route
const express = require('express');
const cors = require('cors');
const app = express();
app.get('/products/:id', cors(), (req, res, next) => {
res.json({msg: 'This is CORS-enabled for a Single Route'})
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log(`CORS-enabled server is up on ${port}`);
});
Important gotcha: When it comes to Express middleware, the order is very important. So make sure CORS is enabled before any other controller/ route/ middleware which may depend on it.
You dont need to enable cors in angular, this is a server side issue. See:
https://stackoverflow.com/a/29548846/4461537
I want to connect with socket.io to a backend that uses express.
the backend is used as api for other functionalities. So, I use some middleware to add headers to express (you could see that in the code).
the problem is that the socketio on the client side gives the following error:
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'.
but I need to keep the '*' to allow all users from any where to access my api.
var express = require('express'); var server = express();
var app = require('http').Server(server);
var io = require('socket.io')(app);
io.set( "Access-Control-Allow-Origin", "*" );
require('./controllers/watsonIoT.controller').startWatson(io);
server.use(function(request, response, next) { // configuration of headers
response.header("Access-Control-Allow-Origin", "*");
response.header("Access-Control-Allow-Headers", "Content-Type, x-auth");
response.header("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT")
next();
})
.use('/gui', express.static('views'))
.use(bodyParser.json())
.use('/api', mainRouter)
.get('*', (req, res) => res.redirect('/'))
.listen(PORT,function(){
console.log("Starting ... port: "+ PORT);
// startWatson();
});