Unexpected Access-Control-Allow-Origin error - javascript

I'm following a simple tutorial from here:
http://addyosmani.github.io/backbone-fundamentals/
I have a node.js server running on a localhost port 4711
I have tomcat running on port 8082 and a backbone.js app as client started as index.html on that server.
But I get :
XMLHttpRequest cannot load ... api/books. Origin localhost:8082 is not
allowed by Access-Control-Allow-Origin.
1) Why? This is not file based access - indeed a plain web browser will see
htttp://localhost:4711/ and interact just fine.
2) What's the fix? (Given that part of this stack is a node.js server)

You're initiating a CORS request since the two servers are listening on different ports( index.html on localhost:8082 and your node server on localhost:4711)
In your node's http server, try setting the Access-Control-Allow-Origin header to * or to the Origin header.
http.createServer(function(req, res) {
res.header('Access-Control-Allow-Origin', req.headers['origin']);
//handle
});

Related

How can I query localhost server from my website with javascript?

I have a website running on, for example, mydomain.com. Then i am starting local backend server at localhost:3000 (127.0.0.1:3000). Can I add some js code to this website so it will query my local backend? Since my browser and my local backend are on same computer I guess it can access my local backend somehow. I tried creating a codepen
https://codepen.io/dranitski/pen/ExNZLJo?editors=1111
with this code:
fetch('http://localhost:3000/').then(r=> r.json().then(j=> console.log('\nREQUEST',j)));
And created test.js file locally with content:
require('http').createServer(function (req, res) { res.end('' + process.pid); }).listen(3000);
then started it with node test.js
But my codepen gives me an error
Uncaught NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://127.0.0.1:3000/'
I can claim backend is working since i can access http://127.0.0.1:3000/ from my browser and see the result successfully.
The idea behind that is to create a website that can interact with backend running locally on user's machine. My users have our backend server started locally and I need an online tool that can query these as well showing them some data from their local backends in human-readable form.
Thanks in advance!
It works!
Just needed to enable cors on local node server
test.js
require('http').createServer(function(req,res){
// Set CORS headers
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Request-Method', '*');
res.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
res.setHeader('Access-Control-Allow-Headers', '*');
res.end('' + process.pid);
}).listen(3000);
then run it with node test.js
Now the pen can access the server!

504 (Gateway Time-out) issue

I have a node/express api deployed (api.mysite.com)
In the express app, I have used app.use(cors());
In the frontend I have a nuxt/vue site (www.mysite.com).
The vue site uses the api to fetch some data. The problem is that most times it works fine. But some times (2 out of 10), I get the following error:
Failed to load resource: the server responded with a status of 504 (Gateway Time-out)
Access to XMLHttpRequest at 'api.mysite.com' from origin 'www.mysite.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I've read a lot but cannot figure out why it's happening specially why only sometimes and not the other times?
Set the timeout to a higher value. If your request is taking more time to be served than the current timeout it throws Gateway Timeout
var server= http.createServer(app).listen(port, function()
{
console.log("Listening on port " + port)
})
server.timeout = 240000;

Angular on Node JS web service - GET http://127.0.0.1 net::ERR_CONNECTION_REFUSED

I am developing website using AngularJS and host it within NodeJS (Express JS) web service. The AngularJS uses the data on some endpoints served by NodeJS. In another word, the NodeJS has endpoints which serve AngularJS web page and providing data needed.
Before host the webpage on my virtual machine (web service), I use my host machine to host it. The webpage then tried to request the data to my virtual machine's endpoint and it works fine.
However, when I'm hosting it on my virtual machine (web service) and changed to request data on my localhost (http://127.0.0.1:3000/data), I am now getting GET http://127.0.0.1:3000/data net::ERR_CONNECTION_REFUSED error.
What I have tried
First, I thought it was occurred because of cross origin resource sharing, so I am enabling that in my NodeJS by adding these lines of code (taken from this site):
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();
});
However, it still does not help at all. I am still getting the same error message.
Later, I thought it probably my firewall was blocking the access. I then turned off my firewall and it still failed to fix my problem.
I believe it happened because of my webpage trying to access endpoint on its localhost API, which should be overcome with CORS handling on my first attempt.
What is causing this exactly if it is not CORS? How do I overcome this issue? Any help would be appreciated.
Update: Node JS Route Code
var express = require('express');
var app =express();
app.use(express.static(path.join(__dirname, 'public')));
app.get('/admin/login/:user/:pass', function(appReq,appRes){
appRes.status(200).send('1');
appRes.end();
});
app.get('/*', function(appReq, appRes){
fs.readFile('./public/index.html', function(err,data){
if (err) {
appRes.writeHead(500);
appRes.end('Error loading html');
}
else {
appRes.writeHead(200);
appRes.end(data);
}
});
});
app.listen(port, function(){
console.log('express app listening at http://'+hostname+":"+port+'/');
});
Here is my AngularJS GitHub repo
Turns out using localhost IP is wrong. It is probably due to the JavaScript is sent to the client and the browser then interprets localhost is the client's localhost. Therefore, changing the localhost to my actual IP address solved my problem.

info - unhandled socket.io url

I'm trying to use sockets to connect to a Node server I'm running localy
but I keep on getting 'info - unhandled socket.io url' on the server side
+
"XMLHttpRequest cannot load http://localhost:8080/socket.io/?EIO=3&transport=polling&t=1424356590540-0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access." on chrome (using address localhost:8000/index.html)
// top six lines of code to see setup
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
server.listen(8080);
also I'm using python SimpleHTTPServer on port 8000
client code is:
var socket = io.connect('http://localhost:8080');
socket.on('connection', function(){
console.log("connected")
});
using https://cdn.socket.io/socket.io-1.3.4.js" version of sockets.io
I'm assuming the html is irrelevant since I don't have any javascript code in it (except references to angular and jquery)
That's a problem with CORS.
Since your web page is on localhost:8000 and the Socket.io server is on localhost:8080 (two different ports, so two different servers), to allow async requests between the two of them you need to enable CORS. Browsers require that for security reasons.
Your server seems to be using Express. Enabling CORS in Express is quite easy, thanks to NPM packages like cors. Alternatively, look at some questions on SO, like: How to allow CORS?

Running https not on 443 how is this possible?

If I hit my domain on any other port other than 443 I get the error below. How is it possible then to use nodejs https on different port?
Secure Connection Failed
An error occurred during a connection to mysite:8080. SSL received a record that exceeded the maximum permissible length. (Error code: ssl_error_rx_record_too_long)
For example, in the example given in the documentation they use port 8000.
// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
Using CentOS 6.
record_too_long often/usually means you sent non-SSL-data to a client expecting SSL.
Try to visit your site and port via HTTP (not HTTPS). If it works, you have accidentally bound an HTTP server to it, not an HTTPS server.
At this very moment I have a Node.js server running on port 3000 using HTTPS.
SSL_ERROR_RX_RECORD_TOO_LONG seems to indicate that there's a problem with the hostname (Source)
The error you've included mentions mysite:8080 which tells me that you're trying to connect to mysite:8080 and that that address doesn't exist.
To debug this, try accessing the URL through a browser or by setting up a regular HTTP and see whether it's accessible.

Categories