nodejs xhr POST - javascript

I am using nodejs and trying to make a POST command to a server. I am also using node-xmlHttpRequest (driverdan's module). I am having issues with the content-type and get the error:
{
"response":{
"errorCode":"UNKNOWN_ERROR","message":"Content type
'text/plain;charset=UTF-8' not supported","detail":"Content type
'text/plain;charset=UTF-8' not supported"
},"version":"1.0"
}
I need the content-type to be JSON, not text. I have tested the code with GET and it works fine.
Here is my code:
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
var sys = require('util');
var json_text2 = { "username": "admin","password": "-----" };
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
//- var xmlHTTP = new XMLHttpRequest();
xhr.onreadystatechange = function() {
sys.puts("State: " + this.readyState);
if (this.readyState === 4) {
sys.puts("Complete.\nBody length: " + this.responseText.length);
sys.puts("Body:\n" + this.responseText);
}
};
xhr.open("POST",apic_url,true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Accept","application/json");
xhr.responseType = 'JSON';
xhr.send(JSON.stringify(json_text2));
app.locals.apic_nd = xhr.responseText;
Any ideas?

Thanks to jfriend00 I got it working (not sure how to upvote his comment. But here is the code I used:
var apicem_ip = "sandboxapic.cisco.com:9443";
var apic_url = 'https://'+apicem_ip+'/api/v1/ticket';
var request = require('request');
var options = {
url: 'https://'+apicem_ip+'/api/v1/ticket',
method: "POST",
headers: {
'Content-type': 'application/json'
},
body: '{ "username": "admin", "password": "----"}'
};
function callback(error, response, body) {
console.log("callback function");
if (!error) {
var info = (JSON.parse(body));
console.log(info);
console.log("status 200");
}
else {
console.log(JSON.parse(body));
}
}
request.post(options, callback);

Related

How to send an Json in GET method in JavaScript?

Hi I'm trying to translate a code in python to Javasrcipt.
import requests
url = "myApi"
r = requests.get(url, json = {"from": "default", "to": "default"})
dic = r.json()
I don't know how to do it in Javascript. Please help me!!!!
Try this:
const url = "myApi";
fetch(`${url}?${new URLSearchParams({
from: "default",
to: "default",
})}`)
.then(res => res.json())
.then(result => console.log('myApi response', result))
you can use XMLHttpRequest :
let xhr = new XMLHttpRequest();
let url = "url?data=" + encodeURIComponent(JSON.stringify({"from": "default", "to": "default"}));
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.from + ", " + json.to);
}
};
xhr.send();

get Id from online hosted Json

I'm trying to get back my jason data that i saved online with the ID that the hosting service set up for me..
const app = new Vue({
el:'#app',
data:{
input:'',
method:'',
status:'200',
timeStart:0,
timeEnd:0,
},
mounted(){
},
methods:{
http_request(){
const url = 'https://' + this.input;
const currentDate = new Date();
this.timeStart = currentDate.getTime();
axios.get(url)
.then(res => {
let parser = document.createElement('a');
parser.href = url;
const protocol = parser.protocol;
const hostname = parser.hostname; // => "example.com"
const pathname = parser.pathname; // => "/pathname/"
const status = res.status;
const method = this.method;
console.log(status, method);
var resp = {
"status": status,
"errors": {},
"data": {
"method": method,
"protocol": protocol,
"hostname": hostname,
"pathname": pathname,
}
}
var response = JSON.stringify(resp);
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
console.log(req.responseText);
console.log(req);
}
};
req.open("POST", "https://api.jsonbin.io/v3/b", true);
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("X-Master-Key", "myapikey");
req.send(response);
const currentDate = new Date();
this.timeEnd = currentDate.getTime();
console.log((this.timeEnd-this.timeStart)/1000);
console.log(resp)
I'm able to save the json so far on https://jsonbin.io/... and it looks like this:
BIN ID: 6069e05f8be464182c5881f0
{
"status": 200,
"errors": {},
"data": {
"method": "get",
"protocol": "https:",
"hostname": "my-json-server.typicode.com",
"pathname": "/lalith1403/jsonemaillist/list"
}
}
the BIN ID is the unique ID that I need in order to show only the desired jason data.. I saw it in the response metadata but I cannot fina a way to get it..
this is the response after the json is saved:
{"record":{"status":200,"errors":{},"data":{"method":"","protocol":"https:","hostname":"my-json-server.typicode.com","pathname":"/lalith1403/jsonemaillist/list"}},"metadata":{"id":"6069e6a07d0d5e1833cee3f9","createdAt":"2021-04-04T16:17:36.929Z","private":true}}
My idea is then to make a new call with the Id attached to the url in order to get the unique data but I could be wrong..
Thx for your support
Based off their documentation, you'd definitely be able to do this! As part of the URL for the read request, you just need to do a GET request on the following URL: https://api.jsonbin.io/v3/b/<BIN_ID>/latest (you may have been missing this "latest" end of the URL, which specifies which version of the BIN_ID you want - the 1st version, 2nd version after it's been updated, 3rd, etc. Latest will just get the most recent one, which I assume is what you want.
That could look something like this:
let id = "assigned id here"
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
console.log(req.responseText);
console.log(req);
}
};
req.open("GET", "https://api.jsonbin.io/v3/b/" + id + "/latest", true);
req.setRequestHeader("Content-Type", "application/json");
req.setRequestHeader("X-Master-Key", "myapikey");
req.send(response);

How to convert ajax request from jQuery pure js?

I need to convert this jquery ajax to Javascript.
$("#newsLetter-form").on('submit',function(event){
event.preventDefault();
email = $('#emailId').val();
console.log(email);
$.ajax({
url: '/subscribes/emailSubscribe',
type:'POST',
data:{
"_token": "{{ csrf_token() }}",
email:email,
},
success:function(response){
console.log(response);
$('#responseFromSub').text("Registred!");
$('#responseFromSub').css('background','lightgreen')
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
error:function(response){
console.log(response);
var val = 'asdasd:111122:123123123';
var response1 = response.responseJSON.message.substring(response.responseJSON.message.indexOf("\"title\":"));
response1 = response1.split(":").pop();
response1 = response1.split(',')[0];
response1 = response1.replace("\"", "");
response1 = response1.replace("\"", "");
console.log(response1);
$('#responseFromSub').text(response1);
$('#responseFromSub').css('background','red');
$('#newsLetter-form').css('display','none');
$('.sucsessMessage').fadeIn(1);
setTimeout(function(){$('.sucsessMessage').fadeOut(1);$('#newsLetter-form').css('display','flex');},3000);
},
});
});
I was googling a lot but I don't how can I push my data by this url in pure js.
If someone knows how to do this, please help.
Here is the sample.
const xhr = new XMLHttpRequest();
// listen for `load` event
xhr.onload = () => {
// print JSON response
if (xhr.status >= 200 && xhr.status < 300) {
// parse JSON
const response = JSON.parse(xhr.responseText);
console.log(response);
}
};
// create a JSON object
const json = {
"email": "abc#example.com",
};
// open request
xhr.open('POST', '/subscribes/emailSubscribe');
// set `Content-Type` header
xhr.setRequestHeader('Content-Type', 'application/json');
// send rquest with JSON payload
xhr.send(JSON.stringify(json));

Postman post request works but ajax post does not. Have checked client side js over and over

first question ever on stackoverflow and boy do I need an answer. My problem is that I have an endpoint to create an item, and it works when I send a POST request with Postman. I'm using node and express:
router.post("/", jwtAuth, (req, res) => {
console.log(req.body);
const requiredFields = ["date", "time", "task", "notes"];
requiredFields.forEach(field => {
if (!(field in req.body)) {
const message = `Missing \`${field}\` in request body`;
console.error(message);
return res.status(400).send(message);
}
});
Task.create({
userId: req.user.id,
date: req.body.date,
time: req.body.time,
task: req.body.task,
notes: req.body.notes
})
.then(task => res.status(201).json(task.serialize()))
.catch(err => {
console.error(err);
res.status(500).json({ message: "Internal server error" });
});
});
That endpoint works when I send with Postman and the req body logged with the right values.
But when I send my ajax request, my server code logs the req.body as an empty object ('{}'). Because Postman works I believe the problem is with my client side javascript but I just cannot find the problem. I and others have looked over it a million times but just can't find the problem. Here is my client side javascript:
//User submits a new task after timer has run
function handleTaskSubmit() {
$(".submit-task").click(event => {
console.log("test");
const date = $(".new-task-date").text();
const taskTime = $(".new-task-time").text();
const task = $(".popup-title").text();
const notes = $("#task-notes").val();
$(".task-notes-form").submit(event => {
event.preventDefault();
postNewTask(date, taskTime, task, notes);
});
});
}
function postNewTask(date, taskTime, task, notes) {
const data = JSON.stringify({
date: date,
time: taskTime,
task: task,
notes: notes
});
//Here I log all the data. The data object and all its key are defined
console.log(data);
console.log(date);
console.log(taskTime);
console.log(task);
console.log(notes);
const token = localStorage.getItem("token");
const settings = {
url: "http://localhost:8080/tasks",
type: "POST",
dataType: "json",
data: data,
contentType: "application/json, charset=utf-8",
headers: {
Authorization: `Bearer ${token}`
},
success: function() {
console.log("Now we are cooking with gas");
},
error: function(err) {
console.log(err);
}
};
$.ajax(settings);
}
handleTaskSubmit();
What I would do:
Change header 'application/json' to 'application/x-www-form-urlencoded' since official docs have no info on former one.
Stop using $.ajax and get comfortable with XHR requests, since jquery from CDN is sometimes a mess when CDN get's laggy and XHR is a native implement and available immediately. Yes it's a code mess, but you always know that it is not the inner library logic thing, but your own problem. You blindly use library, that conceals XHR inside and you do not know how to ask the right question "XHR post method docs" because you are not yet comfortable with basic technology underneath.
Save this and import the variable
var httpClient = {
get: function( url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var readyState = xhr.readyState;
if (readyState == 4) {
callback(xhr);
}
};
var queryString = '';
if (typeof data === 'object') {
for (var propertyName in data) {
queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
}
}
if (queryString.length !== 0) {
url += (url.indexOf('?') === -1 ? '?' : '&') + queryString;
}
xhr.open('GET', url, true);
xhr.withCredentials = true;
xhr.send(null);
},
post: function(url, data, callback ) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
var readyState = xhr.readyState;
if (readyState == 4) {
callback(xhr);
}
};
var queryString='';
if (typeof data === 'object') {
for (var propertyName in data) {
queryString += (queryString.length === 0 ? '' : '&') + propertyName + '=' + encodeURIComponent(data[propertyName]);
}
} else {
queryString=data
}
xhr.open('POST', url, true);
xhr.withCredentials = true;
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(queryString);
}
};
usage is as simple as jquery: httpClient.post(Url, data, (xhr) => {})
Check if you have body parser set-up in app.js
var bodyParser = require('body-parser');
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true })); // get information from html forms
if body parser is set-up try changing header to 'multipart/form-data' or
'text/plain'.
For just the sake check req.query
Cheers! :)

How to get all Files Save in Dropbox to my HTML Page

i have save Images in Dropbox using Javascript like that
document.forms.newsletter.addEventListener('submit', function
cb(evt) {
//evt.preventDefault()
// API key from here: https://dropbox.github.io/dropbox-api-v2-
explorer/#files_upload
// need to consider how this gets secured
var TOKEN = ''
var dir = 'blackground/'
var file = document.getElementById('file').files[0]
var promise = new Promise(function (resolve, reject) {
// Dropbox requires application/octet-stream
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
resolve(JSON.parse(xhr.response));
}
else {
reject(xhr.response || 'Unable to upload file');
}
};
xhr.open('POST',
'https://content.dropboxapi.com/2/files/upload');
xhr.setRequestHeader('Authorization', 'Bearer ' + TOKEN);
xhr.setRequestHeader('Content-Type', 'application/octet-
stream');
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({
path: '/' + dir + file.name,
mode: 'add',
autorename: true,
mute: false
}));
xhr.send(file);
})
promise
.then(function (result) {
// Save dropbox response to form
document.getElementById('dropbox').value =
JSON.stringify(result)
// Submit form on successful upload
evt.target.submit()
})
.catch(function (err) {
console.log('a');
})
return false
})
It works fine. But i want to retrieve each Image using Javascript and ajax to display it in my Web Page. How to make it?
I read this Documentation https://www.dropbox.com/developers-v1/core/docs#files-GET that we can make it with Get Verb.
I have make a Get for the API to get All Image like so
$.ajax({
method: "GET",
url: "https://content.dropboxapi.com/1/files/auto/blackground",
dataType: "json",
ContentType:"application/octet-stream",
Authorization:"Bearer token"
});
i get this Error
{error: "Authentication failed"}
error
:
"Authentication failed"
blackground is the folder where are all the Images
Something can help please
It works fine now. I make it like so. Token is my Token for Dropbox.
var token = '';
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var imageUrl = (window.URL || window.webkitURL).createObjectURL(xhr.response);
// display, assuming <img id="image"> somewhere
document.getElementById('image').src = imageUrl;
// download via the download attribute: limited browser support
var a = document.createElement('a');
//a.download = 'test.png';
//a.href = imageUrl;
//a.click();
}
};
xhr.open('POST', 'https://content.dropboxapi.com/2/files/download');
xhr.setRequestHeader('Authorization', 'Bearer ' + token);
xhr.setRequestHeader('Dropbox-API-Arg', JSON.stringify({ path: '/blackground/blackground_logo.jpg' }));
xhr.send();

Categories

Resources