Cross origin requests are only supported for HTTP error - cross-domain

i am using xmlhttpRequest to get data from database but it shows an error cross origin request are only supported for http.
i tried "header('Access-Control-Allow-Origin: *');" in php but still it shows error.
here is my html code
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","devangpatel.host56.com/sample.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
nd here is php
<?php
header('Access-Control-Allow-Origin: *');
$con=mysqli_connect("host","user","password","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM demo");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br>";
}
mysqli_close($con);
?>

Related

xmlhttprequest status is always 0 and no response in responseText

I have written a simple node.js server and and ajax request to send and recieve request respectively. Despite of every change made its not working.this is my node.js server code...
var express=require('express');
var server=express();
server.get('/sampleResponse',function(req,res){
if(req.method=="POST"){
console.log('reache`enter code here`d post');
res.status(200).send('connection successful');
}else if(req.method=="GET"){
console.log('reached get');
res.status(200).send('connection successful');
}
});
server.listen('8001','127.0.0.1');
//////below is my html page... running on localhost:8100
<html>
<head>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script>
function submitLoginDetails(){
var JSONLoginObj={rollNo:document.getElementById("rollNo").value,
password:document.getElementById("password").value};
///////////////////////////////////////////////////////////////
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
var xhrdata = "";
if(xhttp.readyState == 4){
if(xhttp.status == 200)
alert(xhttp.responseText);
else
alert(xhttp.status);
}
};
xhttp.open("GET", "http://localhost:8001/sampleResponse", false);
xhttp.send();
}
</script>
</head>
<body>
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Login Page</h1>
</ion-header-bar>
<ion-content>
<form>
Roll Number:<br><br>
<input type="text" id="rollNo"><br><br>
Password:<br><br>
<input type="text" id="password"><br><br>
<button id="loginButton" onclick="submitLoginDetails();">Login</button>
</form>
<p id="demo"></p>
</ion-content>
</ion-pane>
</body>
</html>
when access the same page by clicking on link i get response but no response in xhttp.responseText.
This is a cross domain issue (CORS) which means you are trying to make a request (for a resource) from outside of your current domain. You need to allow set the Access-Control-Allow-Origin to accept all your requests.
You can do this by adding the below lines to your .js file (where you have your express.js code)
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin' : '*'
});

How can I deploy the auth0 app to bluemix

I am using a sample project from auth0.com to customize the login page for my app and enable social media login. However I encounter some problem when I try to deploy it to bluemix.
The video tutorial I follow is https://www.youtube.com/watch?v=sHhNoV-sS_I&t=559s
however the sample project is a little bit different from the one in video. It required the command "npm serve" to run it. When I push my project using cf push it shows noappdecked. How can I deploy my project to bluemix?
the app.js code and html code is like
<!DOCTYPE html>
<html>
<head>
<title>Auth0-VanillaJS</title>
<meta charset="utf-8">
<!-- Auth0 lock script -->
<script src="//cdn.auth0.com/js/lock/10.3.0/lock.min.js"></script>
<script src="auth0-variables.js"></script>
<script src="app.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<img alt="avatar" id="avatar" style="display:none;">
<p>Welcome <span id="nickname"></span></p>
<button type="submit" id="btn-login">Sign In</button>
<button type="submit" id="btn-logout" style="display:none;">Sign Out</button>
</body>
window.addEventListener('load', function() {
var lock = new Auth0Lock(AUTH0_CLIENT_ID, AUTH0_DOMAIN);
// buttons
var btn_login = document.getElementById('btn-login');
var btn_logout = document.getElementById('btn-logout');
btn_login.addEventListener('click', function() {
lock.show();
});
btn_logout.addEventListener('click', function() {
logout();
});
lock.on("authenticated", function(authResult) {
lock.getProfile(authResult.idToken, function(error, profile) {
if (error) {
// Handle error
return;
}
localStorage.setItem('id_token', authResult.idToken);
// Display user information
show_profile_info(profile);
});
});
//retrieve the profile:
var retrieve_profile = function() {
var id_token = localStorage.getItem('id_token');
if (id_token) {
lock.getProfile(id_token, function (err, profile) {
if (err) {
return alert('There was an error getting the profile: ' + err.message);
}
// Display user information
show_profile_info(profile);
});
}
};
var show_profile_info = function(profile) {
var avatar = document.getElementById('avatar');
document.getElementById('nickname').textContent = profile.nickname;
btn_login.style.display = "none";
avatar.src = profile.picture;
avatar.style.display = "block";
btn_logout.style.display = "block";
};
var logout = function() {
localStorage.removeItem('id_token');
window.location.href = "/";
};
retrieve_profile();
});
You would use the package.json method documented at https://console.ng.bluemix.net/docs/runtimes/nodejs/index.html#nodejs_runtime , first to declare the serve package as one of your dependencies, then to indicate what the scripts.start script should do (which is run npm serve). You can use npm init (https://docs.npmjs.com/cli/init) to create a starting package.json file if you don't already have one.

NodeJS Express | ReactJS component causes timeout error while testing a view using Mocha and ZombieJS

I have added to my Node ExpressJS app some components in ReactJS. Since I introduced these components, my tests are failing due to timeout error.
My test suites is including mocha, zombie, chai and sinon, but the first two are enough to reproduce the error.
This is the test:
// tests/home-tests.js
process.env.NODE_ENV = 'test';
var app = require('../index.js');
var Browser = require('zombie');
describe('Homepage Tests', function() {
before(function(){
server = app.listen(3002);
browser = new Browser({ site: 'http://localhost:3002' });
})
it('should render title', function(done){
browser.visit('/', function() {
browser.assert.text('h1', 'A test page for ReactJS');
done();
})
});
after(function(done) {
server.close(done);
});
});
This is the layout:
// views/layouts/main.handlebars
<!doctype html>
<!--[if IE 8]> <html class="ie ie8"> <![endif]-->
<!--[if IE 9]> <html class="ie ie9"> <![endif]-->
<!--[if gt IE 9]><!-->
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Zombie ReactJS Test!</title>
{{{_sections.page_stylesheets}}}
</head>
<body>
{{{body}}}
{{{_sections.page_javascripts}}}
</body>
</html>
This is the view I want to test:
<h1>A test page for ReactJS</h1>
<div id="example"></div>
{{#section 'page_stylesheets'}}
<!-- ReactJS -->
<script src="https://npmcdn.com/react#15.3.1/dist/react.js"></script>
<script src="https://npmcdn.com/react-dom#15.3.1/dist/react-dom.js"></script>
<script src="https://npmcdn.com/babel-core#5.8.38/browser.min.js"></script>
{{/section}}
{{#section 'page_javascripts'}}
<script type="text/babel">
ReactDOM.render(
<p>Hello, world!</p>,
document.getElementById('example')
);
</script>
{{/section}}
I have reproduced the error in this small repo.
It seems that it could be easily fixed with a timeout like it follows:
// tests/home-tests.js
// ...
it('should render title', function(done){
this.timeout(5000);
browser.visit('/', function() {
browser.assert.text('h1', 'A test page for ReactJS');
done();
})
});
However, this doesn't appear to be the most suitable solution. In particular, would you be able to suggest a way to run test only after the page is fully loaded (without timeouts to be set)?
Thank you in advance

Autobahn - Sent non-empty 'Sec-WebSocket-Protocol' header error

I am trying to build a WAMP server using NodeJS, wamp.io, and websocket.io.
Here is the server-side code :
var wsio = require('websocket.io');
var wamp = require('wamp.io');
var socketServer = wsio.listen(9000);
var wampServer = wamp.attach(socketServer);
And I am trying to test the pub-sub via browser using AutobahnJS. Here is the client-side code :
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Wamp Example</title>
</head>
<body>
<ul class="pages">
<li>
<button id="socket">Call</button>
</li>
</ul>
<script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="https://autobahn.s3.amazonaws.com/autobahnjs/latest/autobahn.min.jgz">
</script>
<script>
AUTOBAHN_DEBUG = true;
</script>
<script>
var connection = new autobahn.Connection({
url: 'ws://localhost:9000/',
realm: 'realm1'
});
console.log(connection);
connection.onopen = function (session) {
console.log(session);
// session is an instance of autobahn.Session
};
connection.onclose = function(reason, detail){
console.log(reason);
}
connection.open();
</script>
</body>
</html>
But the connection always got this error :
WebSocket connection to 'ws://localhost:9000/' failed: Error during WebSocket handshake: Sent non-empty 'Sec-WebSocket-Protocol' header but no response was received
This part of code return 'unreachable'
connection.onclose = function(reason, detail){
console.log(reason);
}
Is there any code I missed?

Web Audio API: decodeAudioData doesn't decode opus in Chrome

I'm currently trying to make Opus packets work with Web Audio API. The problem is however, while it should be natively supported by FireFox and Chrome, only FireFox can decode a stream of OPUS samples using decodeAudioData from the Web Audio API. Chrome does recognize the file when I drag the opus file into the browser and it also does play it! So I'm wondering that I may be doing something wrong here causing failure in Chrome.
Then I used some sample code from http://awm.jp/~yoya/js/audio/meow.html just load an opus file and try to decode it. Again Firefox does, and Chrome doesn't. So I'm wondering if someone can confirm my finding or tell me what I'm doing wrong here. Below is the modified version from the earlier link. Thanks!
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15">
<title> decodeAudioData sample </title>
</head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
//$(document).ready(function() {
var catMeowingBuffer = null;
window.AudioContext = window.AudioContext||window.webkitAudioContext;
var context = new AudioContext();
function onError(err) {
console.log("unable to decode");
}
function loadCatSound(url) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
// Decode asynchronously
request.onload = function() {
context.decodeAudioData(request.response, function(buffer) {
catMeowingBuffer = buffer;
var src = context.createBufferSource();
src.buffer = catMeowingBuffer
src.connect(context.destination);
src.start(0);
}, onError);
}
request.send();
}
loadCatSound("opus.opus");
function playCatSound() {
if (catMeowingBuffer !== null) {
var src = context.createBufferSource();
src.buffer = catMeowingBuffer
src.connect(context.destination);
src.start(0);
}
}
//});
</script>
<body>
<h1> decodeAudioData sample </h1>
<button onclick="playCatSound();"> playCatSound </button>
<hr>
<address></address>
</body> </html>
This is a bug in Chrome. See https://code.google.com/p/chromium/issues/detail?id=409402.

Resources