Javascript HttpRequest POST Access-Control-Allow-Origin error in web server - javascript

I tried to do HttpRequest by JavaScript. Because I had previously received an Access-Control-Allow-Origin error, I used Python's SimpleHTTPServer. But still I received the Access-Control-Allow-Origin error message. Is there another way? And is there anything wrong with javascript?
Here is my code.
The server needs :
basic Authorization
'Accept' : 'application/json'
'Content-Type' : 'application/json'
'Content-Length' : '*'
body written by JSON
And I used the Chrome browser.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script language="javascript" type="text/javascript">
function OnButtonClick() {
var clientId = "-my ID-";
var clientSecret = "-my password";
var authorizationBasic = window.btoa(clientId + ':' + clientSecret);
var request = new XMLHttpRequest();
request.open('POST', "-my url-");
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.setRequestHeader('Content-Type', 'application/json');
request.send(JSON.stringify({email: "-my email-" }));
request.onreadystatechange = function () {
if (request.readyState === 4) {
alert(request.responseText);
}
};
}
</script>
</head>
<body>
<input id="Button1" type="button" value="送信" onclick="OnButtonClick();" />
<div id="output"></div>
</body>
</html>

Related

Loading Worker from worker.js failed beacuse of disallowed MIME type (“text/html”)

I am trying to implement a simple Web Worker.
https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers
The following is my index.html snippet :
<!DOCTYPE html>
<html>
<head>
<title>Worker</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta content="X-Content-Type-Options=nosniff" http-equiv="Content-Type" />
<link rel="stylesheet" href="css/uikit.min.css" />
<link rel="stylesheet" href="css/font-awesome.min.css">
<script src="js/index.js"></script>
</head>
The follwing is my index.js (Main javascript file) :
var liveWorker;
function spawnLiveWorker()
{
console.log("inside spawnLiveWorker()");
if (typeof(Worker) !== "undefined")
{
if (typeof(liveWorker) == "undefined")
{
liveWorker = new Worker('worker.js');
}
}
else
{
console.error("Sorry, your browser does not support Web Workers...");
}
}
$(document).ready(function() {
console.log("document ready");
spawnLiveWorker();
});
The following is my worker.js :
var curURL = "http://172.30.206.80:8080/dp1_30";
var curAttrib = "2435";
function updateLiveDataWorker()
{
console.log("inside updateLiveDataWorker() in worker");
let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
console.log("response type in updateLiveDataWorker = ",typeof this.response);
console.log("response in updateLiveDataWorker = ",this.response);
//console.log("")
postMessage(this.response)
}
else
{
console.log("error");
}
}
xhr.open("GET", "/api/device/getTimeSeriesDataForLastUpdatedDay");
xhr.setRequestHeader("Authorization", "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJha3NoYXQuc3JpdmFzdGF2YUBtZGx6LmNvbSIsImV4cCI6MTYzNzU3ODg2OSwiaWF0IjoxNjM3NTYwODY5fQ.dUTJ7hm5xnJhBubDKB2F7-Ob2S83hlYmygrhVDFyuWQSmCWJ31vY_laksE0iP0nbyU2Pz2p578mjibCB3PIRUA");
xhr.setRequestHeader("attributeId", curAttrib);
xhr.send();
}
function startUpdatingLiveDataWorker()
{
console.log("inside startUpdatingLiveDataWorker() in worker");
setInterval(updateLiveDataWorker,30000);
}
updateLiveDataWorker();
startUpdatingLiveDataWorker();
However, I am getting this error :
GEThttp://172.30.206.80/worker/worker.js
[HTTP/1.1 404 1ms]
Loading Worker from “http://172.30.206.80/worker/worker.js” was blocked because of a disallowed MIME type (“text/html”).
I have tried adding the following line as meta tag in index.html :
following instructions from the following page :
X-Content-Type-Options

How to test sending form data through Javascript locally?

I'm learning about sending forms through JavaScript by manually building XMLHttpRequest.
In the end of given example, there's a note:
Note: This use of XMLHttpRequest is subject to the same-origin policy if you want to send data to a third party web site. For cross-origin requests, you'll need CORS and HTTP access control.
I'd like to test the example locally, though. What can I change to make it work locally? The address of posting request?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>Click me!</button>
<script>
function sendData(data) {
console.log('Sending data');
const XHR = new XMLHttpRequest();
let urlEncodedData = "",
urlEncodedDataPairs = [],
name;
for (name in data) {
urlEncodedDataPairs.push(encodeURIComponent(name) + '=' + encodeURIComponent(data[name]));
}
urlEncodedData = urlEncodedDataPairs.join('&').replace('/%20/g', '+');
XHR.addEventListener('load', function (event) {
alert('Yeah! Data sent and response loaded.');
});
XHR.addEventListener('error', function (event) {
alert('Oops! Something went wrong.');
});
XHR.open('POST', 'https://example.com/cors.php');
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XHR.send(urlEncodedData);
}
const btn = document.querySelector('button');
btn.addEventListener('click', function () {
sendData({ test: 'ok' });
})
</script>
</body>
</html>
You can use a fake REST API service, like https://reqres.in. Basic usage is free and requires no registration whatsoever.
They usually send back fake data and don't require CORS.
You just need to change the URL to https://reqres.in/api/users for example.

Trying to run a console log on php file storing json but callback error and 404 (not found)

Working with trying to learn json and ajax and how they interoperate with html and javascript
I have a php with json data inside
I am trying to get the json data formatted into the html page but I keep getting error that "callback is not a function"
I am running the php and html files on my MAMP server to simulate a api feed
I will share my html and js files
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="run2.js"></script>
<title>Ajax Demo</title>
</head>
<body>
<h1 class="title">Todays Weather Forecast</h1>
<p class="sub">Click the button the check the local weather.</p>
<button class="demo-centered" type="button" onclick="loadPhp()">Check Weather</button><br><br>
<p id="demo"></p>
</body>
</html>
var loadPhp = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
callback(null, xhr.response);
} else {
callback(status);
}
};
xhr.send();
};
loadPhp('demo.php', function (err, data) {
if (err != null) {
alert('Something went wrong: ' + err);
} else {
for (var i = 0; i < data.length; i++) {
for (x in data[i]) {
console.log(data[i][x]);
}
}
}
});
PHP just in case
{"coord":{"lon":-116.8,"lat":33.03},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":293.73,"feels_like":289.89,"temp_min":289.26,"temp_max":295.93,"pressure":1016,"humidity":52},"visibility":16093,"wind":{"speed":5.7,"deg":260},"clouds":{"all":40},"dt":1589408840,"sys":{"type":1,"id":5686,"country":"US","sunrise":1589374130,"sunset":1589423903},"timezone":-25200,"id":5391832,"name":"San Diego County","cod":200}
You have to create a javascript function called callback to do what the you want the callback to do.

HTTP request Readystate=4 and Status=400

Im trying to make a POST call on a JSON based API, but im keep getting Status:400, bad request.
Here is my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API TEST</title>
</head>
<body>
<button onclick="myFunction()">Test</button>
<div id="result"></div>
<script>
function myFunction() {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
//alert(this.status);
alert(this.readyState);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhr.open("POST", URL);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({username: "test", password: "test"}))
}
</script>
</body>
</html>

How to get google plus user image?

I tried to search on stackoverflow but all answer not work.
This is my code for get google plus user image, but not work.
How can i do that ?
<html>
<head>
<script src="https://apis.google.com/js/plusone.js"></script>
<script type="text/javascript">
function onSignin(e){
accessToken = e.access_token;
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://www.googleapis.com/plus/v1/people/me/");
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.send();
xhr.onreadystatechange = function(){
if (this.readyState == 4){
var myProfile = JSON.parse(xhr.responseText);
alert(myProfile.image.url);
}
}
}
</script>
</head>
<body>
<g:plus action="connect" clientid="100009709084787102522" scope="https://www.googleapis.com/auth/plus.me" callback="onSignin">
</g:plus>
</body>
</html>

Categories