Javascript code works in Chrome, but not in other browsers - javascript

I created simple web page using react and express. One module contains simple form with text input field, email input field and submit button and on submit it should send the mail to me, containing data from input fields. I used nodemail to create this sending mail thing! Luckily it works on chrome, unluckily it doesnt work on other browsers( firefox, IE, chrome on mobile ).
I found out that the problem is not in the backend side, but in the function connecting frontend with backend, but after that I got stuck and dont know what to do :(
onSubmit = e => {
var newMessage = {
msg_sender: this.state.msg_sender,
msg_content: this.state.msg_content
}
axios.post("http://localhost:4000/message", newMessage)
.then(res => console.log(res.data))
.catch(err => console.log("Error! " + err)
);
};
That is the part connecting frontend with backend - as I said, it works fine in chrome, but doesnt in other browsers.

Arrows functions are still a relatively new feature in JavaScript and unfortunately some browsers are still not up-to-date and likely never will be able to support them (Looking at you Internet Explorer).
There's a couple of ways to work around this.
1) You could rework all your arrow functions into standard functions:
onSubmit = function(e){
var newMessage = {
msg_sender: this.state.msg_sender,
msg_content: this.state.msg_content
}
var axiosSetup = axios.create({
baseURL: "http://localhost:4000"
})
axiosSetup.post("/message", newMessage)
.then(function(res){ console.log(res.data) })
.catch(function(err){ console.log("Error! " + err) })
);
};
2) You can integrate Babel in your application, which is a compiler that converts your javascript into compatible code for all browsers:
https://babeljs.io/
If you're building application for browser-compatibility it will also be in your best interest to check out mozilla's web developer guide which is a great reference to check if your code will work on other browsers.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Alternatively, you can also use JavaScript's native fetch API. The benefit being that you do not have to install any libraries and its setup for use will be the same across all browsers
onSubmit = function(e){
var newMessage = {
msg_sender: this.state.msg_sender,
msg_content: this.state.msg_content
}
fetch('http://localhost:4000/message', {
method: 'POST',
body: newMessage
})
.then(function(res){ console.log(res.json()) })
.catch(function(err){ console.log("Error! " + err) })
};
See documentation here:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Related

Greetings! I want to read json file locally without Internet through simple HTML and JS, after running the code it throws an error here is my code

fetch("./my_json_file.json")
.then(response => {
return response.json();
})
.then(data => {
mydata = data;
console.log("this is " + mydata)
console.log("now " + mydata)
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).PolarArea(mydata);
});
[enter image description here](https://i.stack.imgur.com/IS6FU.png)
https://www.tutorialstonight.com/read-json-file-in-javascript
I tried these above three methods I get what I do not needed.
Recommended: use a web server. Web browsers do not allow access to local files for security reasons. You can use the Live Server extension for VS Code and it will be local and offline (no internet connection needed).
NOT recommended: you might be able to launch your web browser with the --allow-file-access-from-files command-line flag. But that will make you vulnerable to security risks! Web browsers might not support that command-line flag anymore.

Javascript fetch stopped working for local files

I have a tiny HTML/CSS/JS app I use to read and play certain types of files. I have no need for it to be on a server.
As of yesterday, it "worked." Suddenly, today I'm getting an error about using fetch with local files. I did make some settings changes on my Windows 10 laptop.
abcjs-init.js:15 Fetch API cannot load file:///E:/OneDrive/Documents/ABCJS-Minimal-Editor-Notation-Player/tunes/tune_list.txt. URL scheme "file" is not supported.
This is my code:
fetch(tunes_list_path, {mode: 'no-cors'})
.then(response =>
{
console.log("response:", response);
return response
})
.then(data =>
{
console.log("data:", data)
return data.text()
})
.then(Normal =>
{
console.log("got tunelist");
console.log("tune_list");
let tune_list = Normal.split("\n").sort();
addTunesToSelector(tune_list);
})
.catch(err =>
{
console.log('Fetch problem show: ' + err.message);
});
Further up is: let tunes_list_path = "tunes/tune_list.txt";.
The index.html loads fine. I can also view the file in the error directly with its URL. So it is visible to the browser.
Do I need to enable something in my browser? Add something to the fetch call?
Aha! I had changed a setting in Firefox that allowed COORS with local files: privacy.file_unique_origin.
I apparently erased that setting during my OS maintenance.
This solution is only for FF. There may be an equivalent setting for Chromium-based browsers.

Fetch failing for Post to API

I have a route on my express server: /api/users/register.
When I pass data through VIA postman I am able to register an account. However on the front-end react side I am getting: TYPE ERROR: Failed to Fetch. Here is the code
handleSubmit = (event) => {
event.preventDefault();
const isValid = this.validateForm();
console.log(isValid);
if(isValid) {
let user = {
"username" : this.state.username,
"email" : this.state.email,
"password" : this.state.password
}
var json = JSON.stringify(user);
console.log(user);
fetch('https://URL/api/user/register', {
method: 'POST',
body: json,
headers: {
'Content-Type' : 'application/json'
}
}).then(function() {
console.log('ok');
}).catch(function(err){
console.log(err);
});
}
}
Its failing on the client side and I am not sure why. I am using POST methods else where and those are working just fine. I am stuck and have been for the last day. Any ideas on what's going on?
EDIT: I realize I am getting: ERR_CERT_COMMON_NAME_INVALID from Chrome on the URL but now I am not sure how to fix this.
You are likely hitting the changes in the way latest Chrome handles SSL certs. As of Chrome 58 I believe, they deprecated CNs altogether so if you are using self-signed dev certificate (or certificate that does not have proper SAN/Subject Alternative Name) you are likely to see this error. There has been a fair bit of commotion as many commercial products now find their code broken in Chrome.
Here is Google support article on the subject: https://support.google.com/chrome/a/answer/7391219
The best solution would be to update the server certs. If it is not feasible AND you are running on Windows, in some limited number of cases you could use this registry hack as a temporary workaround:
[HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome]
"EnableCommonNameFallbackForLocalAnchors"=dword:00000001
Hope that helps

CF Connect to the cloud controller

I use the following lib to connect to the cloud controller
https://github.com/prosociallearnEU/cf-nodejs-client
const endpoint = "https://api.mycompany.com/";
const username = "myuser";
const password = "mypass";
const CloudController = new (require("cf-client")).CloudController(endpoint);
const UsersUAA = new (require("cf-client")).UsersUAA;
const Apps = new (require("cf-client")).Apps(endpoint);
CloudController.getInfo().then((result) => {
UsersUAA.setEndPoint(result.authorization_endpoint);
return UsersUAA.login(username, password);
}).then((result) => {
Apps.setToken(result);
return Apps.getApps();
}).then((result) => {
console.log(result);
}).catch((reason) => {
console.error("Error: " + reason);
});
I try to run it against our API and its not working and Im not getting no error message in the console, what it can be ?
where does the space/org is handled here ? since when I connect from the cli it ask me to which space/org I want to connect...
Im able to login via the CLI, just from the code I cant, any idea what is missing here?
The issue it when I run it I dont get any error that can help to understand what is the root cause
I cloned the original git repository and modified some methods to support proxy. Please note that I modified just some methods to get the sample code working, but a complete refactor of the package is needed.
Basically what you have to do is to add a proxy parameter before calling the request method (this is done throughout the package, so several modifications are needed), for example this is for one of the methods in the Organization.js file:
getSummary (guid) {
const url = `${this.API_URL}/v2/organizations/${guid}/summary`;
const proxy = `${this.API_PROXY}`;
const options = {
method: "GET",
url: url,
proxy: proxy,
headers: {
Authorization: `${this.UAA_TOKEN.token_type} ${this.UAA_TOKEN.access_token}`
}
};
return this.REST.request(options, this.HttpStatus.OK, true);
}
You can find my changes in the git repository below:
https://github.com/adasilva70/cf-nodejs-client.git
I have also created a new sample below. This sample lists all organizations for a user, gets the first organization returned and lists its spaces. You can modify the code to provide a similar functionality that cf login provides (allow you to select an organization then a space).
const endpoint = "https://api.mycompany.com/";
const username = "youruser";
const password = "yourpassword";
const proxy = "http://proxy.mycompany.com:8080";
const CloudController = new (require("cf-nodejs-client")).CloudController(endpoint, proxy);
const UsersUAA = new (require("cf-nodejs-client")).UsersUAA;
const Apps = new (require("cf-nodejs-client")).Apps(endpoint, proxy);
const Orgs = new (require("cf-nodejs-client")).Organizations(endpoint, proxy);
CloudController.getInfo().then((result) => {
console.log(result);
UsersUAA.setEndPoint(result.authorization_endpoint, proxy);
return UsersUAA.login(username, password);
}).then((result) => {
//Apps.setToken(result);
//return Apps.getApps();
Orgs.setToken(result);
return Orgs.getOrganizations();
}).then((result) => {
console.log(result);
org_guid = result.resources[1].metadata.guid;
return Orgs.getSummary(org_guid);
}).then((result) => {
console.log(result);
}).catch((reason) => {
console.error("Error: " + reason);
});
I have done just minor tests to make sure the sample works, so use carefully. Also, the changes will only work for a case where proxy is needed now.
The first thing that strikes me on the library's github site is the warning:
Note: This package is not ready for a production App yet.
It also seems that the project is not being maintained as there are a number of tickets ooened that are quite a few months old that don't have a response.
Anyway, to figure out why the library is not working and producing no error message, I would check out the library source code and add some console logging statements, probably starting with the HttpUtils. For example:
requestWithDefaults(options, function (error, response, body) {
console.log("requestWithDefaults error: ", error)
console.log("requestWithDefaults response: ", response)
console.log("requestWithDefaults body: ", body)
...
}
Alternatively, you could try debugging the code by adding breakpoints to the requestWithDefaults and other key places in the library, using the nodejs debugger.
You could also try debugging the network calls similar to this how to monitor the network on node.js similar to chrome/firefox developer tools?
To understand how to use the library, I would take a look into the tests folder and look for a test that is similar to your use case. There are a reasonable amount if tests that look useful in the test/lib/model/cloudcontroller folder.
As for the question about spaces, I have found an example where you can pass in a space guid to return apps for that space guid.
CloudFoundrySpaces.getSpaceApps(space_guid, filter).then( ... )
I'm assuming the call you are using App.getApps() will return Apps for all spaces/organizations.

Fido U2F client side javascript source code

I'm looking for a JavaScript source code (client side) to make communication between Fido U2F token and Google Chrome (Version 41.0.2272.89 m).
Please help me
Here is an example to getting the Token response for registration using Yubico u2f-api file
var RegistrationData = {"challenge":"dG7vN-E440ZnJaKQ7Ynq8AemLHziJfKrBpIBi5OET_0",
"appId":"https://localhost:8443",
"version":"U2F_V2"};
window.u2f.register([RegistrationData], [],
function(data) {if(data.errorCode) {
alert("U2F failed with error: " + data.errorCode);
return;
}
alert(JSON.stringify(data));
});
you've to include the u2f-api.js and use an Https server
You can perform the registration, and even parse the registrationData using Javascript
let registerRequest = {
challenge: 'RegisterChallenge',
version: 'U2F_V2'
}
u2f.register('https://localhost', [registerRequest], [],
(response) => {
U2FRegistration.parse(response.registrationData);
console.log(U2FRegistration);
}
);
Here is a github repo demonstrating this: https://github.com/infiniteloopltd/U2FJS - and as mentioned, you need a HTTPS server, and include u2f-api.js

Categories

Resources