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.
Related
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())
I have server and a client the server uses node js the client send requests to the sever and the server should act accordingly.
However I came across a little bit of a confusing behavior and i want to know why its behaving like that!
The thing is when i send a json array or Object the received data by the server is always empty for some reason.
Here is the code of the request that raises the problem:
function Save()
{ // saves the whole global data by sending it the server in a save request
if( global_data.length > 0)
{
var url = "http://localhost:3000/save";
var request = new XMLHttpRequest();
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json");
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
console.log(this.responseText);
}
};
let object={ id: "101.jpg", RelativePath: "images/101.jpg", size: 61103 }; // this just an exemple of data
let data_json = JSON.stringify(object);
request.send(data_json);
}
else
{
console.log("Nothing to save");
}
}
And Here is the server code related to this request:
const server=http.createServer(onRequest)
server.listen(3000, function(){
console.log('server listening at http://localhost:3000');
})
function onRequest (request, response) {
/*function that handles the requests received by the server and
sends back the appropriate response*/
/*allowing Access-Control-Allow-Origin since the server is run on local host */
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Request-Method', '*');
response.setHeader('Access-Control-Allow-Methods', 'OPTIONS, GET');
response.setHeader('Access-Control-Allow-Headers', '*');
console.log("a request received :" ,request.url);
let parsed_url = url.parse(request.url);
if(parsed_url.pathname == '/save')
{
console.log("Proceeding to save state : ...");
let received_data = '';
request.on('data', function(chunck) {
received_data += chunck;
console.log("another line of data received");
});
request.on('end', function() {
console.log(received_data); // why is this empty (my main problem)?
let jsondata = JSON.parse(received_data); // here raises the error since the received data is empty
console.log(jsondata);
response.writeHeader(200,{"content-Type":'text/plain'});
response.write("SAVED!");
response.end()
});
}
}
Just if anyone got the same problem: for me I couldn't solve it directly so I was forced to use query-string in order to parse the data instead of json.parse it seems the data received emptiness was related to the failure of the JSON parser somehow. so I installed it with npm install querystring and used const qs = require('querystring'); in order to invoque the parser by calling qs.parse(received_data.toString());.
Hope this helps anyone who got stuck in the same situation.
I've got a request from an html page to a Node service.
The service works perfectly in Firefox and Chrome when accessed through url. Works perfectly when I use curl and also with Postman.
When I use XMLhttpsRequest it launches the onerror associated function and end up with readyState 4, status 0.
I don't know why, at a given time Firefox let me know through the developer's console that I was cross accessing (Tho I am accessing localhost, but I won't loose it for it) (By the way: I never received the "crossing" message again I surely touch a sensible key with my console.logs that I should have erased)
So I incorporated this midleware to my server:
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();
});
When I run it in Chrome it says:
GET https://localhost:3000/oficina/9999 net::ERR_CONNECTION_CLOSED
I swear that's not true.
My Ajax code is this:
function accede(accion,url,fn) {
var xobj = new XMLHttpRequest();
// console.log("accion: ", accion);
// console.log("url : ", url);
xobj.overrideMimeType("application/json");
xobj.open(accion, url, true);
xobj.onerror = (e) => {
alert("Error del Navegador!!!\nStatus: " +xobj.status +" (" +xobj.statusText+")")
console.log("Falló, Header:")
console.log(xobj.headers)
}
xobj.onprogress = (e) => {
console.log("Progress: ")
}
xobj.onreadystatechange = () => {
console.log("State:",xobj.readyState,"Status:", xobj.status)
if (xobj.readyState == 4 && xobj.status == "200") {
console.log("Fifó!")
}
};
xobj.onload = () => { fn(JSON.parse(xobj.responseText)) };
xobj.send();
}
The whole code is in:
https://github.com/elmasbestia/bnsvr
May somebody help me?
why don't you get the javascript code from postman
I tried 2 methods . from chrome and form console. both work
I get 500's due to exception on the server though
also, why are you using https? i don't see your express server being https
I am following this tutorial to upload a video to blob storage - https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-blob.html#step1
I have done all of them including enabling CORS.
Currently I have set CORS to enable * for max period.
But i am still getting
Failed to load resource: the server responded with a status of 400 (Bad Request)
:9000/#/:1 Failed to load https://XXXXXX.blob.core.windows.net/3d7959e4-a48d-447b-a919-
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://localhost:9000' is
therefore not allowed access. The response had HTTP status code 400.
I had it working two days ago, but it just suddenly stopped working.
Here is my javascript on how I am calling.
var blobUri = 'https://XXXXXX.blob.core.windows.net/';
var sastoken = 'XXXXXX';
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, sastoken);
var customBlockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 * 512;
blobService.singleBlobPutThresholdInBytes = customBlockSize;
var customediaid = mediaid;
//Guid
//Wrong guid here- create a proper one
var customazureid = guid + ".mp4";
var finishedOrError = false;
var speedSummary = blobService.createBlockBlobFromBrowserFile(
customediaid,
customazureid,
file,
{ blockSize: customBlockSize },
function (error, result, response) {
finishedOrError = true;
if (error) {
console.log(error);
alert('Failed look console');
} else {
alert('Success - Check folder named -' + mediaid + "with filename - " + customazureid + '.mp4');
UpdateDatabase(mediaid, azuremediaid);
}
}
);
Have my cors enabled like this for the storage account.
ALLOWED ORIGINS ALLOWED METHODS ALLOWED HEADERS EXPOSED HEADERS MAX AGE
* GET,HEAD,POST,PUT,OPTIONS,MERGE,DELETE * * 2147483647
Also in the tutorial website, you can list all the containers using SAS token and storage account. That also works when I add in those fields. It just wont work in my site.
Edit
Not sure if this helps, but here is how the request looks like by using the postman tool to capture them.
https://XXXXX.blob.core.windows.net/02b8be3e-22b7-41fc-a1d3-831153f8de90/97d603e4-767d-ddc2-169a-379db3af7419.mp4?comp=block&blockid=Njc4YTA4Nz
Request Headers
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:en-US,en;q=0.9
Access-Control-Request-Headers:content-type,x-ms-client-request-id,x-ms-date,x-ms-version
Access-Control-Request-Method:PUT
Connection:keep-alive
DNT:1
Host:XXXXXXX.blob.core.windows.net
Origin:http://localhost:9000
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
Respone I get is -
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource.
Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 403.
According to your description, I just reused your code with my azure blob storage as follows:
<script type="text/javascript" src="https://brucchstorage.blob.core.windows.net/scripts/azurestoragejs-0.2.8-preview/azure-storage.blob.js"></script>
<script type="text/javascript">
function uploadfile() {
var blobUri = 'https://brucchstorage.blob.core.windows.net';
var blobService = AzureStorage.Blob.createBlobServiceWithSas(blobUri, 'st=2018-04-04T21%3A41%3A00Z&se=2018-04-05T21%3A41%3A00Z&sp=rw&sv=2017-04-17&sr=c&sig=D1HX40pFCONuWGKTCKCYXyWvbwuErrog6yTfk%2FZBQ1A%3D');
// If one file has been selected in the HTML file input element
var file = document.getElementById('fileinput').files[0];
var customBlockSize = file.size > 1024 * 1024 * 32 ? 1024 * 1024 * 4 : 1024 * 512;
blobService.singleBlobPutThresholdInBytes = customBlockSize;
var finishedOrError = false;
var speedSummary = blobService.createBlockBlobFromBrowserFile('images', file.name, file, { blockSize: customBlockSize }, function (error, result, response) {
finishedOrError = true;
if (error) {
// Upload blob failed
alert("error:" + error);
} else {
// Upload successfully
alert("success");
}
});
}
</script>
If I do not configure the CORS for my blob storage, I would retrieve the following error:
Then, I used Azure Storage Explorer to set the CORS as follows:
TEST:
Moreover, I would recommend you open a new incognito window to narrow down this issue.
This is my very first question I am posting on StackOverflow. I usually tend to find answers to any question I have for whatever project, but I am really stuck on this one. I'm writing a Chrome extension that attempts to send JSON-objects over a HTTP post request with certain data in it to a basic Java server that will -in a later stage- process some of the data and return a HTTP response with relevant (processed) information for the client. This is the relevant JavaScript snippet on client-side:
function postRequest(jsonObject) {
var param = JSON.stringify(jsonObject);
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log(request.response);
}
};
request.open("POST", "http://"+link);
request.setRequestHeader("Content-type","text/plain");
request.send(param);
// request.abort();
}
The input JSON-object is legit and the link-item is the predefined host IP of the server. The server-side code is Java-based and is the following:
public class Server {
public static void main(String args[]) throws Exception {
while (true) {
try {
ServerSocket ss = new ServerSocket(1024);
Socket s = ss.accept();
System.out.println("Request: ");
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
PrintWriter pw = new PrintWriter(s.getOutputStream());
String line;
while ((line = br.readLine()) != null) {
if (line.length() == 0) {
break;
}
System.out.print(line + "\r\n");
}
System.out.println("");
System.out.println("Response:");
String response = "HTTP/1.1 200 OK \r\n" + "Access-Control-Allow-Origin: * \r\n"
+ "Connection: close \r\n" + "\r\n";
System.out.println(response);
pw.write(response);
while ((line = br.readLine()) != null) {
if (line.length() == 0) {
break;
}
System.out.print(line + "\r\n");
}
br.close();
pw.close();
System.out.println("");
System.out.println("Socket Closed");
System.out.println("");
s.close();
ss.close();
} catch (Exception ex) {
// Do whatever
}
}
}}
The server does receive the request and the JSON-object, but no response is received on client side (readyState is usually 4, but status code is 0 and responseText is empty). Additionally the connection is not closed when I don't use request.abort() or close the extension's window. It for sure has nothing to do with the permissions in the manifest file, so I didn't include it in this post. Can somebody see what my mistake is or anybody have had a similar experience?
EDIT:
The HTTP request is received on server side and looks like:
POST / HTTP/1.1
Host: [IP address of the server; I deleted the exact address for privacy]
Connection: keep-alive
Content-Length: 173
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36
Origin: chrome-extension://nhpingbdjkkljheamibjobneeehiednk
Content-type: text/plain
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: nl-NL,nl;q=0.8,en-US;q=0.6,en;q=0.4,fr;q=0.2
Since the request is received on server side, I figured that the actual sending of the response is currently unsuccessful. Might it have something to do with the origin domain of the client? When I copy-paste that domain in my browser, I get a ERR_FILE_NOT_FOUND.