Ionic/Angular HTTP post request not working on android - javascript

I used Angular HTTP while testing in the browser and it worked fine, but it doesn't on an actual mobile device... Apparently HTTP angular doesn't work on mobile and I had to convert the post request to ionic native HTTP. I'm not sure if it's converted correctly and what the issue is...
Also, the get requests work fine is only the post requests that don't work.
Hope someone can help me with this. Thanks in advance!
My code :
angular HTTP post request
senduserdata(username){
var dataToSend = {
username:this.Username,
password:this.Password,
usertype:this.getSelectedSubject,
}
var url = 'https://mylink.herokuapp.com/login';
this.http.post(url,{data:JSON.stringify(dataToSend)},{responseType: 'text'}).subscribe(
(data)=>{
alert(data);
if(data === "Logged In Successfully!")
{
this.LoginCustomer();
this.cartservice.setUsernameCustomer(this.Username);
}
else if(data === "Welcome!")
{
this.LoginStaff();
this.cartservice.setUsernameStaff(this.Username);
}
}
)
}
ionic advanced HTTP post request
senduserdata(){
var dataToSend = {
username:this.Username,
password:this.Password,
usertype:this.getSelectedSubject,
}
var url = 'https://mylink.herokuapp.com/login';
this.http.post(url,{data:JSON.stringify(dataToSend)},{responseType: 'text'}).then(
(data)=>{
this.message= JSON.parse(data.data);
alert(this.message)
if(this.message === "Logged In Successfully!")
{
this.LoginCustomer();
this.cartservice.setUsernameCustomer(this.Username);
}
else if(this.message === "Welcome!")
{
this.LoginStaff();
this.cartservice.setUsernameStaff(this.Username);
}
}
)
}

Update
Turns out it works on the browsers cause I was using CORS changer extensions,
I just had to add in my node.js file
app.all('*', function(req, res, next) {
var origin = req.get('origin');
res.header('Access-Control-Allow-Origin', origin);
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
var app = express();
var cors = require('cors');
app.use(cors())

Related

Problems to get POST response JavaScript front / node js back

im trying to connect to my local node server route (http://localhost:3000/user-ragnarok-controller/saveragnarokuser/) from my javascript application and im getting no response from it. The server is receiving the request and is processing the same, but i cant get the response at client side.
my javascript app are running at localhost:80 (Apache XAMPP) and my node server at localhost:3000.
this is my javascript code to connect to node server end-point:
function handler() {
alert('handler');
if(invocation.readyState === XMLHttpRequest.DONE && invocation.status === 200) {
alert('entrei aqui');
console.log(invocation.responseText);
} else
alert('nao foi hj ' + invocation.status.toString());
}
function saveUser() {
alert('dourado ');
var eml = document.getElementById('emailInputRegister');
var user = document.getElementById('userInputText');
var sx = document.getElementById("sexInputSelected");
var selectedSex = sx.options[sx.selectedIndex].value;
var pwd = document.getElementById("passwordInputRegister");
var uri = 'http://localhost:3000/user-ragnarok-controller/saveragnarokuser/';
var body = {
'userid': user.value,
'userpass': pwd.value,
'email': eml.value,
'sex': selectedSex
};
invocation.open('POST', uri);
invocation.withCredentials = true;
invocation.setRequestHeader('Content-Type', 'application/json');
invocation.onreadystatechange = this.handler;
invocation.send(JSON.stringify(body));
}
this is my request at google chrome console
Now let's talk about the server side. Here i have a middleware for CORS treatment.
// Add headers
app.use(function (req, res, next) {
console.log('reqHeaders: ' + JSON.stringify(req.headers));
res.header('Access-Control-Allow-Origin', 'http://localhost');
res.header('Access-Control-Allow-Headers', 'content-type');
res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.header('Access-Control-Allow-Credentials', true);
if(req.method === 'OPTIONS')
return res.status(200).send({});
next();
});
After CORS, the server starts my route POST:
router.post('/saveragnarokuser',function(req,res,next){
console.log('######################### Iniciando saveragnarokuser.');
UserRagnarokController.addUser(req.body,function(err,count){
if(err){
console.log('entrei aqui error: ' + err);
res.json(err);
}
else{
console.log('entrei aqui ok');
var userObj = {
response: "OK"
};
res.status(200).json(userObj);
}
});
});
looking to the server log its possible to see the request coming, processing, but for some reason the POST response is -- ms --. With no Status and execution time.
reqHeaders: {"host":"localhost:3000","connection":"keep-alive","content-length":"88","user-agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36","content-type":"application/json","accept":"*/*","origin":"http://localhost","sec-fetch-site":"same-site","sec-fetch-mode":"cors","sec-fetch-dest":"empty","referer":"http://localhost/co-cadastro/register.html?","accept-encoding":"gzip, deflate, br","accept-language":"pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7"}
######################### Iniciando saveragnarokuser.
myReqbody: {"userid":"fernandocabeca","userpass":"1234","email":"acosta.aluiz#gmail.com","sex":"F"}
POST /user-ragnarok-controller/saveragnarokuser/ - - ms - -
entrei aqui ok
My function UserRagnarokController.addUser performed perfectly, the requisition data was successfully filled in the database, i just need to get this response at client side (google chrome app), i got no error and no success.
NOTE: when I execute the request at POSTMAN it works normally, the answer is 200 OK.
There is probably a warning in the browser's console about breaking of CORS policy.
Headers about CORS should come from your server (Response Headers) and I don't see that tab here in your screenshot.
Postman ignores CORS, and server process all request by default.

Displaying Data on Website from Node.js (Without Frameworks)

I have a Node.js webserver and I am fetching data from a mysql Server. The fetched Data needs to be displayed now in the frontend as HTML. I am not allowed to use any 3rd Party node.js/JavaScript framework's.
I'm new to Webserver development and i'm having a hard time figuring out how to "transport" the Backend Data to the Frontend.
I have 2 Ideas in my mind but dont know what's the right way to approach this problem...
Send Data via JSON to Client and process it with JavaScript. (Possible? and if yes how?)
Before sending the HTTP response, parse the HTML and insert the data. (Complicated without using Frameworks and too costly ?)
What would be the right way to solve this problem ?
Any Help would be appreciated. Thank's.
Solved it like this:
app.js
var http = require('http');
var url = require('url');
var server = http.createServer(function(req, res) {
var q = url.parse(req.url, true);
if(q.filename == "command"){
res.writeHead(200, {'Content-Type':'application/json'});
return res.end(some_json);
}
}
index.html
<script>
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://localhost:8000/command", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
//Process Data
var jsonObj = JSON.parse(xmlhttp.responseText);
document.getElementById("test").innerHTML = jsonObj;
}
}
xmlhttp.send();
</script>
<div id="test"></div>
Something like this?
const http = require('http');
const util = require('util');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
mysql.query("select * from table").then(rows => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/html');
res.end(`<html><head></head><body>${util.inspect(rows)}</body></html>`);
})
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

jQuery getJSON fails with 404 error

The URL that the getJSON request is sent to definitely exists, but the request fails with a 404 error. The URL just hosts a JSON object: here. I've also tried using the same request but replacing the destination with a local JSON file hosted in the same directory, which also fails with a 404 error. I'm guessing this
means that the error is either with my getJSON request, or with my node.js server configuration.
This is the function that makes the getJSON call:
function loginFunction(){
//check browser support
if(typeof(Storage) !== "undefined"){
//store dat shit
sessionStorage.setItem("username", document.getElementById('username').value);
sessionStorage.setItem("password", document.getElementById('password').value);
$(document).ready(function(){
$.getJSON(createUsernameURL(), function(data){
console.log(data);
var responseUsername = data.username;
document.getElementById("unresult").innerHTML = responseUsername;
var responsePassword = data.password;
document.getElementById("pwresult").innerHTML = responsePassword;
});
});
}else{
document.getElementById("pwresult").innerHTML = "your browser is out of date";
}
And this is the config file for my node.js server:
const http = require('http');
const express = require('express');
const app = express();
app.listen(3000,function(){
console.log(__dirname)
});
app.get('/', (req,res) => {
res.sendFile(__dirname + '/index.html');
});
app.use("/static", express.static(__dirname + '/static'));
The createUsernameURL() function just appends a couple pieces of user-entered information to a base URL, but even hard-coding the exact database link mentioned above gives the same issues.

How do you send a post via XMLhttprequest to my own Node server in vanilla javascript?

I am trying to send data to node via a XMLhttprequest. The data looks like this (/q/zmw:95632.1.99999.json). My connection to Node is correct, however, I was getting an empty object so I set the headers to Content-Type application/json and then stringified the data. However Node gives me a Unexpected token " error. I presume it is because of the string, however, if I don't stringify the data then it errors out because of the "/" in the data. How do i properly send the data using pure Javascript. I want to stay away from axios and jquery because I want to become more proficient in vanilla javascript. I will make the final call to the api in node by assembling the url prefix and suffix.
Here is my code:
function getCityForecast(e){
//User selects option data from an early JSONP request.
var id = document.getElementById('cities');
var getValue = id.options[id.selectedIndex].value;
//Assembles the suffix for http request that I will do in Node.
var suffix = getValue + ".json";
var string = JSON.stringify(suffix);
console.log(suffix);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(string);
}
Node.js code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var path = require('path');
var request = require('request');
var http = require('http');
// ****************** Middle Ware *******************
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
app.post('/', function(req, res){
console.log('working');
console.log(req.body);
});
app.listen(3000, function() { console.log('listening')});
I figured it out my mistake and this was my problem. I was trying to send a string instead of an object. So it wasn't proper JSON like this:
var string = JSON.stringify(suffix);
To remedy the situation I added:
var newObj = JSON.stringify({link : suffix});
This allowed my post to be successful because I was now sending an object hence the word Javascript Object Notation.
This is working for me, at the moment. The REST API I'm hitting requires a token. Yours might not, or it might be looking for some other custom header. Read the API's documentation. Note, you might need a polyfill/shim for cross browser-ness (promises). I'm doing GET, but this works for POST, too. You may need to pass an object. If you're passing credentials to get a token, don't forget window.btoa. Call it like:
httpReq('GET', device.address, path, device.token).then(function(data) {
//console.log(data);
updateInstrument(deviceId,path,data);
}, function(status) {
console.log(status);
});
function httpReq(method, host, path, token) {
if(method === "DELETE" || method === "GET"|| method === "POST" || method === "PUT" ){
var address = 'https://' + host + path;
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(method, address, true);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader ("X-auth-token", token);
//xhr.setRequestHeader ("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function() {
var status = xhr.status;
if (status == 200 || status == 201 || status == 202) {
resolve(xhr.response);
}
// this is where we catch 404s and alert what guage or resource failed to respond
else {
reject(status);
}
};
xhr.send();
});
} else {
console.log('invalid method');
}
};

How to call json api and and add it to html page via node.js

Im sorry if this may be a dumb question but i hit a wall and been trying to figure this out for hours.
How to call json api and and add it to html page via node.js
my api address is localhost:8080/api I'm routing my html page to index.html.
I'm guessing it to make son an array and then call array in html? I have n idea how to do that.
please help me out. thanks.
server.js`
var util = require('./util.js');
//call random gen - return string with 9 length.
var output = util.stringGen(9);
console.log(output);
var express = require('express');
var app = express();
var path = require('path');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.get('/api', function(req, res){
res.json({healthy: output})
});
app.listen(8080);
Your question is how to call your server from your client.
You might choose different approaches depending on what client you are using.
For native javascript, you can try reading here or if you are using AngularJS, see how to use $http
The URL you would want to call is `http://localhost:8080/api'
To hit api on client side, you need to use XMLHttpRequest . I've added a simple example of how to do that using github api and displaying the response in the label field. Although you can display response in any way you want :
<body>
<script>
function httpGet(theURL) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", theURL);
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
var response = null;
if(xmlHttp.readyState == XMLHttpRequest.DONE) {
response = xmlHttp.responseText;
document.getElementById("response").value = response;
}
};
}
</script>
<input id="clickMe" type="button" value="get Data"
onclick="httpGet('https://api.github.com/search/users?q=rohankanojia')" />
<br>
Response : <input id="response" type="label"/>
</body>

Categories