Send data to a server remote server with javascript - javascript

I send data from one server to another with XMLhttpRequest but this code doesn't work:
var AjaxURL = 'http://localhost:5000/index.html';
$.ajax({
type: "GET",
url: AjaxURL,
data: {
foo: "test01"
},
success: function(result) {
window.console.log('Successful');
}
});
(Console log:
"Successful")
I have tried it with an iframe and it works but I need to send it with ajax or XMLhttpRequest.
const socket = io();
let params = new URLSearchParams(location.search);
let a1 = params.get('foo');
socket.emit('data', a1);
socket.on('data', (data) => {
const fileName = './src/data.json';
const file = require(fileName);
file.data = data;
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
if (err) return console.log(err);
console.log('writing to ' + fileName + ':' + data);
});
})
{"data":"testing"}
Thanks

Related

sending json object to Django framework returns a 500 code error

I am sending an object using AJAX to a Django view. The data I am sending is mouse movement which is sent every 10 seconds to the server to be saved. Now, I have no problem reading my data from the client and server sides. The data gets saved in the database, but I get a 500 error message every time the function sends to the server gets executed. I tried to use fetch and got this error message:
POST error: SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
I searched about this error, and my understanding is that the problem is with the data type, but I am unsure how I can trace the problem and fix it. Could someone help me troubleshoot this issue?
here is my js function:
var target_id = '';
var eventsLog = {"mouse": []};
function logMouse(event){
target_id = event.target.id;
currDate = new Date()
start_time = currDate.getHours() + ':' + currDate.getMinutes() + ':' + currDate.getSeconds() + ':' + currDate.getMilliseconds();
var insert = [start_time, target_id];
(eventsLog.mouse).push(insert);
}
var timesPerSecond = 5;
var wait = false;
$(document).on('mousemove', function (event) {
if (!wait) {
logMouse(event);
wait = true;
setTimeout(function () {
wait = false;
}, 1000 / timesPerSecond);
}
});
const post_url = server_url;
function sendMovement() {
/* fetch(post_url, {
method: 'POST',
body: JSON.stringify(eventsLog),
credentials: 'include',
headers: {'Content-Type': 'application/json'}
}).then(res => res.json()).then(response => {
console.log('POST response:', response);
}).catch(error => {
console.log('POST error:', error);
});*/
$.ajax({
type: "POST",
url: server_url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(eventsLog),
dataType: "json",
success: function () {
},
error: function (req, textStatus, errorThrown){
console.log('Ooops, something happened: ' + textStatus + ' ' +errorThrown)
}
});
and this is my Django view:
movement = json.loads(request.body.decode('utf-8'))
and I checked the data type received in Django and it is a dictionary.
Retrieve csrftoken from cookies and attach it on the request header. Use setInterval() to send the request every ten seconds. Of course you can implement with Fetch API, but since you were using jQuery on your movement function, I also used it to send an AJAX.
get_mouse_movement.html
(just the script part)
<script>
var target_id = '';
var eventsLog = {"mouse": []};
var timesPerSecond = 5;
var wait = false;
function getCookie(name) {
...
}
function logMouse(event){
target_id = event.target.id;
currDate = new Date()
start_time = currDate.getHours() + ':'
+ currDate.getMinutes() + ':'
+ currDate.getSeconds() + ':'
+ currDate.getMilliseconds();
console.log([start_time, target_id])
eventsLog.mouse.push([start_time, target_id]);
};
$(document).on('mousemove', function (event) {
if (!wait) {
logMouse(event);
wait = true;
setTimeout(function () {
wait = false;
}, 1000 / timesPerSecond);
}
});
function sendLog() {
$.ajax({
type: "POST",
url: '/your/url/',
headers: {'X-CSRFToken': getCookie('csrftoken'), 'Content-Type': 'application/json'},
data: JSON.stringify(eventsLog),
success: function(data) {
console.log(data.message);
eventsLog.mouse = [];
},
});
};
setInterval(function(){
sendLog();
}, 10000);
</script>
views.py
import json
from django.http import JsonResponse
def mouse_movement(request):
if request.method == 'POST':
data = json.loads(request.body)
print(data)
return JsonResponse({'message': 'log is saved'})
return render(request, 'get_mouse_movement.html')
.loads() accepts, str, bytes or bytearray. You do not need to decode it.

Getting "No file" or empty file when trying to download PDF file with Node.js

The issue:
I need to download a PDF file from my server but getting either "No file" or empty file
Details:
Here is my server-side code:
let fileBuffered = '';
// authentication for downloading a file from Dropbox API to my server
const dropbox = dropboxV2Api.authenticate({
token: process.env.DEV_DROPBOX_SECRET_KEY
});
// configuring parameters
const params = Object.freeze({
resource: "files/download",
parameters: {
path: `/${customerFileFolder}/${fileName}`
}
});
let dropboxPromise = new Promise(function (resolve, reject) {
dropbox(params, function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
}).on('data',function(data) {
fileBuffered += data;
})
const file = fileBuffered;
res.setHeader("Content-Type", "application/octet-stream");
res.send(file);
The PDF file's that I'm trying to download size is 139,694 bytes. The length of the fileBuffered variable is 132,597. Here is the content of the variable as it is shown in the debugger:
Seems like a legit PDF file
Here is the client-side
function documentFileDownload(fileName) {
const ip = location.host;
let request = $.ajax({
type: "POST",
url: `${http() + ip}/documentFileDownload`,
headers: {
"Accept": "application/octet-stream"
},
data: {
fileName: fileName
},
error: function (err) {
console.log("ERROR: " + err);
}
});
console.log(request);
return request;
}
Problem:
Then I get the response on a client-side it looks like this:
Note the size of the responseText: 254Kb.
What I actually get in the browser is a "Failed - No file" message
What else I tried:
I tried to play with different Content-Types (application/pdf, text/pdf) on a server-side and tried to convert the variable to base64 buffer
const file = `data:application/pdf;base64, ${Buffer.from(fileBuffered).toString("base64")}`;
and added res.setHeader("Accept-Encoding", "base64");
but still getting the same result.
Any ideas?
I found a solution. I missed a .on("end", ) event while reading data from Dropbox stream. Here is a working solution:
Here is the server-side:
let chunk = [];
let fileBuffered = '';
// authentication for downloading a file from Dropbox API to my server
const dropbox = dropboxV2Api.authenticate({
token: process.env.DEV_DROPBOX_SECRET_KEY
});
// configuring parameters
const params = Object.freeze({
resource: "files/download",
parameters: {
path: `/${customerFileFolder}/${fileName}`
}
});
let dropboxPromise = new Promise(function (resolve, reject) {
dropbox(params, function (err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
}).on('data',function(data) {
fileBuffered += data;
}).on('end', () => {
// console.log("finish");\
// generate buffer
fileBuffered = Buffer.concat(chunk);
});
const file = `data:application/pdf;base64, ${Buffer.from(fileBuffered).toString("base64")}`;
res.setHeader("Content-Type", "application/pdf");
res.send(file);
Client-side:
function documentFileDownload(fileName) {
const ip = location.host;
let request = $.ajax({
type: "POST",
url: `${http() + ip}/documentFileDownload`,
responseType: "arraybuffer",
headers: {
"Accept": "application/pdf"
},
data: {
fileName: fileName
},
error: function (err) {
console.log("ERROR: " + err);
}
});
// console.log(request);
return request;
}
Try adding dataType: "blob" in your $.ajax method
and within the headers object add this 'Content-Type', 'application/json'.

AJAX not uploading images to backend service

Working on a requirement to upload images to AWS instance. UI and service is separated and connects via REST. Service is in nodejs. from UI we are making a ajax call to backend service to upload the images to AWS.
The problem:
When I upload the images via POSTMAN request, I can see that response as uploaded with files properly uploaded in AWS.
Whereas when I upload images via AJAX call, I get no response in browser, and also the images are not uploaded in aws.
Below is the piece of code in ajax:
var formData = new FormData();
formData.append('image', $('#tx_file_programa')[0]);
$.ajax({
method: 'POST',
type: "POST",
url: 'http://10.0.0.95:9999/photo/1',
contentType: false,
processData: false,
async: false,
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + access_token );
},
data: formData,
success: function (data) {
console.log('response from server is : ', data);
}
//dataType: 'json'
});
This is the backend service.
server.post('/photo/:count', function (req, res) {
if (req.getContentType() == 'multipart/form-data') {
var form = new formidable.IncomingForm(),
files = [], fields = [];
var result = [];
var noOfFiles = req.params.count;
var count = 0;
console.log('noOfFiles', noOfFiles);
form.on('field', function(field, value) {
fields.push([field, value]);
console.log(fields);
})
form.on('progress', function(bytesReceived, bytesExpected) {
console.log('err');
});
form.on('error', function(err) {
console.log('err',err);
});
form.on('aborted', function() {
console.log('aborted', arguments);
});
new Promise(function(resolve, reject) {
var result = [];
form.onPart = function (part) {
var data = null;
const params = {
Bucket: 'xxxxx',
Key: uuidv4() + part.filename,
ACL: 'public-read'
};
var upload = s3Stream.upload(params);
upload.on('error', function (error) {
console.log('errr', error);
});
upload.on('part', function (details) {
console.log('part', details);
});
upload.on('uploaded', function (details) {
let extension = details.Location.split('.');
if(['JPG', 'PNG'].indexOf(extension[extension.length - 1].toUpperCase()) > -1) {
var ext = extension[extension.length - 1];
count++;
result.push(details.Location);
if(count == noOfFiles) {
resolve(result);
}
}
});
part.pipe(upload);
}
}).then(function(result){
console.log('end', result);
res.writeHead(200, {'content-type': 'text/plain'});
res.end('received files:\n\n ' + util.inspect(result));
})
form.parse(req, function (err, fields, files) {
})
return;
} else {
BadRequestResponse(res, "Invalid request type!");
}
})
#user3336194, Can you check with this, this is working thins
var appIconFormData = null
$(":file").change(function () {
var file = this.files[0], name = file.name, size = file.size, type = file.type;
var imageType = new Array("image/png", "image/jpeg", "image/gif", "image/bmp");
if (jQuery.inArray(type, imageType) == -1) {
return false;
} else {
appIconFormData = new FormData();
appIconFormData.append('appimage', $('input[type=file]')[0].files[0]);
}
});
$.ajax({
url: 'your/api/destination/url',
type: 'POST',
data: appIconFormData,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data)
},
error: function (e) {
}
});
I think the way you are sending formdata is not correct.
Try these 2 ways:
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);

Post - Cannot GET error - Local server

I am trying to create an API using a local server for testing. The route
'GET' works fine, however 'POST' has a problem and it is returning 'Cannot GET /add/name'. I am developing the API using node.js and Express. Why am I receiving get when the route is set to 'POST'? Where is the problem?
var fs = require('fs');
var data = fs.readFileSync('events.json');
var allEvents = JSON.parse(data);
console.log(allEvents);
console.log('Server running.');
var express = require('express');
var app = express();
var sever = app.listen(3000, listening);
function listening() {
console.log('Serving...');
}
app.use(express.static('website'));
//GET and send all data from JSON
app.get('/all', sendAll);
function sendAll(request, response) {
response.send(allEvents);
}
//POST new data to JSON
app.post('/add/:name', addData);
function addData(request, response) {
var newData = request.params;
var name = newData.name;
var eventType = newData.eventType;
var reply;
// var newEvent = {
// name: ":name",
// eventType: ":eventType",
// };
var newData = JSON.stringify(allEvents, null, 2);
fs.writeFile('events.json', newData, finished);
function finished(err) {
console.log('Writting');
console.log(err);
var reply = {
word: word,
score: score,
status: 'Success'
}
response.send(reply);
}
}
Request
$(function() {
//HTML
var $list = $('#list');
var jsonURL = '../events.json'
$.ajax({
type: 'GET',
url: '/all',
success: function(data) {
console.log('Data received', data);
$.each(data, function (type, string) {
$list.append('<li>' + type + " : " + string + '</li>');
});
},
error: function (err) {
console.log('Error, data not sent.', err);
}
});
$('#submit').on('click', function () {
// var newEvent = {
// name: $name.val(),
// eventType: $eventType.val(),
// };
var name = $('#fieldName').val();
var eventType = $('#fieldEventType').val();
console.log(name);
$.ajax({
type: 'PUT',
url: '/add/' + name,
success: function (addData) {
$list.append('<li>name: ' + name + '</li>');
},
error: function (err) {
console.log('Error saving order', err);
}
});
});
});
Thank you in advance.
For testing POST request, you can use Postman to test it. If you use the browser to call the api, it will be GET method instead of POST.

Create GitHub repo from node.js

I have this function in my node project, that should create a new GitHub repository for a specific user:
exports.create_repo = function (repo) {
var options = {
host: "api.github.com",
path: "/user/repos?access_token=" + repo.accessToken,
method: "POST",
json: { name: repo.name },
headers: { "User-Agent": "github-app" }
};
var request = https.request(options, function(response){
var body = '';
response.on("data", function(chunk){ body+=chunk.toString("utf8"); });
response.on("end", function(){
var json = JSON.parse(body);
console.log(json);
});
});
request.end();
}
Every time I use it, the response is:
{ message: 'Not Found',
documentation_url: 'https://developer.github.com/v3' }
What do I do wrong ?

Categories

Resources