Pure JavaScript Send POST Data Without a Form - javascript

Is there a way to send data using the POST method without a form and without refreshing the page using only pure JavaScript (not jQuery $.post())? Maybe httprequest or something else (just can't find it now)?

You can send it and insert the data to the body:
var xhr = new XMLHttpRequest();
xhr.open("POST", yourUrl, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: value
}));
By the way, for get request:
var xhr = new XMLHttpRequest();
// we defined the xhr
xhr.onreadystatechange = function () {
if (this.readyState != 4) return;
if (this.status == 200) {
var data = JSON.parse(this.responseText);
// we get the returned data
}
// end of state change: it can be after some time (async)
};
xhr.open('GET', yourUrl, true);
xhr.send();

The Fetch API is intended to make GET requests easy, but it is able to POST as well.
let data = {element: "barium"};
fetch("/post/data/here", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
}).then(res => {
console.log("Request complete! response:", res);
});
If you are as lazy as me (or just prefer a shortcut/helper):
window.post = function(url, data) {
return fetch(url, {method: "POST", headers: {'Content-Type': 'application/json'}, body: JSON.stringify(data)});
}
// ...
post("post/data/here", {element: "osmium"});

You can use the XMLHttpRequest object as follows:
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.send(someStuff);
That code would post someStuff to url. Just make sure that when you create your XMLHttpRequest object, it will be cross-browser compatible. There are endless examples out there of how to do that.

Also, RESTful lets you get data back from a POST request.
JS (put in static/hello.html to serve via Python):
<html><head><meta charset="utf-8"/></head><body>
Hello.
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "/postman", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
value: 'value'
}));
xhr.onload = function() {
console.log("HELLO")
console.log(this.responseText);
var data = JSON.parse(this.responseText);
console.log(data);
}
</script></body></html>
Python server (for testing):
import time, threading, socket, SocketServer, BaseHTTPServer
import os, traceback, sys, json
log_lock = threading.Lock()
log_next_thread_id = 0
# Local log functiondef
def Log(module, msg):
with log_lock:
thread = threading.current_thread().__name__
msg = "%s %s: %s" % (module, thread, msg)
sys.stderr.write(msg + '\n')
def Log_Traceback():
t = traceback.format_exc().strip('\n').split('\n')
if ', in ' in t[-3]:
t[-3] = t[-3].replace(', in','\n***\n*** In') + '(...):'
t[-2] += '\n***'
err = '\n*** '.join(t[-3:]).replace('"','').replace(' File ', '')
err = err.replace(', line',':')
Log("Traceback", '\n'.join(t[:-3]) + '\n\n\n***\n*** ' + err + '\n***\n\n')
os._exit(4)
def Set_Thread_Label(s):
global log_next_thread_id
with log_lock:
threading.current_thread().__name__ = "%d%s" \
% (log_next_thread_id, s)
log_next_thread_id += 1
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
Set_Thread_Label(self.path + "[get]")
try:
Log("HTTP", "PATH='%s'" % self.path)
with open('static' + self.path) as f:
data = f.read()
Log("Static", "DATA='%s'" % data)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(data)
except:
Log_Traceback()
def do_POST(self):
Set_Thread_Label(self.path + "[post]")
try:
length = int(self.headers.getheader('content-length'))
req = self.rfile.read(length)
Log("HTTP", "PATH='%s'" % self.path)
Log("URL", "request data = %s" % req)
req = json.loads(req)
response = {'req': req}
response = json.dumps(response)
Log("URL", "response data = %s" % response)
self.send_response(200)
self.send_header("Content-type", "application/json")
self.send_header("content-length", str(len(response)))
self.end_headers()
self.wfile.write(response)
except:
Log_Traceback()
# Create ONE socket.
addr = ('', 8000)
sock = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(addr)
sock.listen(5)
# Launch 100 listener threads.
class Thread(threading.Thread):
def __init__(self, i):
threading.Thread.__init__(self)
self.i = i
self.daemon = True
self.start()
def run(self):
httpd = BaseHTTPServer.HTTPServer(addr, Handler, False)
# Prevent the HTTP server from re-binding every handler.
# https://stackoverflow.com/questions/46210672/
httpd.socket = sock
httpd.server_bind = self.server_close = lambda self: None
httpd.serve_forever()
[Thread(i) for i in range(10)]
time.sleep(9e9)
Console log (chrome):
HELLO
hello.html:14 {"req": {"value": "value"}}
hello.html:16
{req: {…}}
req
:
{value: "value"}
__proto__
:
Object
Console log (firefox):
GET
http://XXXXX:8000/hello.html [HTTP/1.0 200 OK 0ms]
POST
XHR
http://XXXXX:8000/postman [HTTP/1.0 200 OK 0ms]
HELLO hello.html:13:3
{"req": {"value": "value"}} hello.html:14:3
Object { req: Object }
Console log (Edge):
HTML1300: Navigation occurred.
hello.html
HTML1527: DOCTYPE expected. Consider adding a valid HTML5 doctype: "<!DOCTYPE html>".
hello.html (1,1)
Current window: XXXXX/hello.html
HELLO
hello.html (13,3)
{"req": {"value": "value"}}
hello.html (14,3)
[object Object]
hello.html (16,3)
{
[functions]: ,
__proto__: { },
req: {
[functions]: ,
__proto__: { },
value: "value"
}
}
Python log:
HTTP 8/postman[post]: PATH='/postman'
URL 8/postman[post]: request data = {"value":"value"}
URL 8/postman[post]: response data = {"req": {"value": "value"}}

You can use XMLHttpRequest, fetch API, ...
If you want to use XMLHttpRequest you can do the following
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
name: "Deska",
email: "deska#gmail.com",
phone: "342234553"
}));
xhr.onload = function() {
var data = JSON.parse(this.responseText);
console.log(data);
};
Or if you want to use fetch API
fetch(url, {
method:"POST",
body: JSON.stringify({
name: "Deska",
email: "deska#gmail.com",
phone: "342234553"
})
}).then(result => {
// do something with the result
console.log("Completed with result:", result);
}).catch(err => {
// if any error occured, then catch it here
console.error(err);
});

There is an easy method to wrap your data and send it to server as if you were sending an HTML form using POST.
you can do that using FormData object as following:
data = new FormData()
data.set('Foo',1)
data.set('Bar','boo')
let request = new XMLHttpRequest();
request.open("POST", 'some_url/', true);
request.send(data)
now you can handle the data on the server-side just like the way you deal with reugular HTML Forms.
Additional Info
It is advised that you must not set Content-Type header when sending FormData since the browser will take care of that.

Did you know that JavaScript has it's built-in methods and libs to create forms and submit them?
I am seeing a lot of replies here all asking to use a 3rd party library which I think is an overkill.
I would do the following in pure Javascript:
<script>
function launchMyForm()
{
var myForm = document.createElement("FORM");
myForm.setAttribute("id","TestForm");
document.body.appendChild(myForm);
// this will create a new FORM which is mapped to the Java Object of myForm, with an id of TestForm. Equivalent to: <form id="TestForm"></form>
var myInput = document.createElement("INPUT");
myInput.setAttribute("id","MyInput");
myInput.setAttribute("type","text");
myInput.setAttribute("value","Heider");
document.getElementById("TestForm").appendChild(myInput);
// To submit the form:
myForm.method = "POST";
myForm.action = "whatever.aspx"; // or "response.php"
myForm.submit();
// This will create an INPUT equivalent to: <INPUT id="MyInput" type="text" value="Heider" /> and then assign it to be inside the TestForm tags.
}
</script>
This way (A) you don't need to rely on 3rd parties to do the job. (B) It's all built-in to all browsers, (C) faster, (D) it works, feel free to try it out.
I hope this helps.
H

navigator.sendBeacon()
If you simply need to POST data and do not require a response from the server, the shortest solution would be to use navigator.sendBeacon():
const data = JSON.stringify({
example_1: 123,
example_2: 'Hello, world!',
});
navigator.sendBeacon('example.php', data);

The most popular answers here do not show how to get data back from the POST. Also, the popular "fetch" solutions do not work in the latest version of Chrome when sending data to the latest version of NodeJS unless you pass headers and also unwrap the response.json() promise. Also, the popular answers do not use async/await.
Here is the cleanest and most complete solution I could come up with that works.
async function postJsonData(jsonObject) {
const response = await fetch("/echo", {
method: "POST",
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(jsonObject)
});
const actualResponse = await response.json();
}

Here is a nice function you (or anyone else) could use in their code:
function post(url, data) {
return new Promise((res, rej) => {
let stringified = "";
for (const [key, value] of Object.entries(data))
stringified += `${stringified != '' ? '&' : ''}${key}=${value}`
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
if (xhr.readyState == 4)
if (xhr.status == 200)
res(xhr.responseText)
else
rej({ code: xhr.status, text: xhr.responseText })
}
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(stringified);
})
}

const data = { username: 'example' };
fetch('https://example.com/profile', {
method: 'POST', // or 'PUT'
headers: {
' Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});

You can also use this: https://github.com/floscodes/JS/blob/master/Requests.js
You can easily send a http-Request. Just use:
HttpRequest("https://example.com", method="post", data="yourkey=yourdata");
That's it! It should even work if the site is CSRF-protected.
Or just send a GET-Request by using
HttpRequest("https://example.com", method="get");

use this func of jbezz library
var makeHttpObject = function () {
try {return new XMLHttpRequest();}
catch (error) {}
try {return new ActiveXObject("Msxml2.XMLHTTP");}
catch (error) {}
try {return new ActiveXObject("Microsoft.XMLHTTP");}
catch (error) {}
throw new Error("Could not create HTTP request object.");
}
function SendData(data){
let type = (data.type ? data.type : "GET")
let DataS = data.data;
let url = data.url;
let func = (data.success ? data.success : function(){})
let funcE =(data.error ? data.error : function(){})
let a_syne = (data.asyne ? data.asyne : false);
let u = null;
try{u = new URLSearchParams(DataS).toString();}catch(e){u = Object.keys(DataS).map(function(k) {return encodeURIComponent(k) + '=' + encodeURIComponent(DataS[k])}).join('&')}
if(type == "GET"){url +="?"+u}
const xhttp = makeHttpObject();
xhttp.onload = function(){func(this.responseText)}
xmlHttp.onreadystatechange = function() {if (xmlHttp.readyState == 4)
{if(xmlHttp.status !== 200){funcE(xmlHttp.statusText)}}}
xhttp.open(type,url,a_syne);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(u);
}
use this to run :
SendData({
url:"YOUR_URL",
asyne:true,
type:"POST", // or GET
data:{
username:"ali",
password:"mypass" // Your Data
},
success:function(Result){
console.log(Result)
},
error:function(e){
console.log("We Have Some Error")
}
});
Or
download jbezz and add to your page.
download link : github.com
use :
$$.api({
url:"YOUR_URL",
asyne:true,
type:"POST", // or GET
data:{
username:"ali",
password:"mypass" // Your Data
},
success:function(Result){
console.log(Result)
},
error:function(e){
console.log("We Have Some Error")
}
});

Related

GET Request with JS

i need to send a GET request from my JavaScript function to my python flask app. However, i tried to type the URL with the parameters manually and it worked. But i can't send the same request in a JS function. Response type is HTML.
This is how the URL should look like:
http://127.0.0.1:5000/books?rank=2&topic=Self improvement
I tried this, but it didn't work:
function sendRequest() {
const xhr = new XMLHttpRequest();
xhr.open('GET', '/books', {
rank: rank,
topic: topic
});
xhr.onload = function() {
console.log(xhr.response);
}
xhr.send();
}
What the URL looked like with this try:
http://127.0.0.1:5000/books
Please help!
You're trying to pass the parameters in a POST body (the third argument to open). That won't work for a GET, they have to be in the URL.
The easiest and least error-prone way is to use URLSearchParams (thank you Christopher for pointing that out when I forgot!):
const url = "/books?" + new URLSearchParams({rank, title});
Live Example:
const rank = 42;
const title = "Life, the Universe, and Everything";
const url = "/books?" + new URLSearchParams({rank, title});
console.log(url);
These days, you'd usually use the more modern fetch rather than XMLHttpRequest:
function sendRequest() {
const url = "/books?" + new URLSearchParams({rank, title});
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
return response.text(); // Or `.json()` or one of the others
})
.then((data) => {
console.log(data);
})
.catch((error) => {
// ...handle/report error...
});
}
But if you prefer to use XMLHttpRequest, put the parameters in the URL (and handle errors):
function sendRequest() {
const xhr = new XMLHttpRequest();
const url = "/books?" + new URLSearchParams({rank, title});
xhr.open("GET", url);
xhr.onload = function () {
console.log(xhr.response);
};
xhr.onerror = function () {
// ...handle/report error...
};
xhr.send();
}
(You can also use string concatenation and encodeURIComponent to build the URL, but it's more work and more error-prone. :-) )
I made a code with fetch() based on the comments above, let me know if you get any errors. Hope this helps, XMLHttpRequest() is not used much due to its complexity.
async function sendRequest(){
const url = 'your URL';
await fetch(url,{
method: "GET",
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
}).then(response=>{
if(response.status !=200) {
throw new Error(`HTTP ERROR:${response.status}`);
}
return response.text()
}
).then(data => {
console.log(data);
// convert to html
}).catch(err => {
console.log(err);
})
}

How can i apply callback to get the http response in a method

I am attempting to write a method so that i pass the url and application name and it return the response. I read that I can apply callback to resolve this but I am not able to resolve the issue. Any help would be appreciated.
Please find below my code snippet.
var response = getResponse(url,applicationName)
console.log("response from getResponse \n" +response);
function getResponse(url,applicationName){
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"application": applicationName
}));
xhr.onload = function() {
console.log(this.responseText);
}
return xhr.responseText;
}
You can use the onreadystatechange method to handle XHR responses, try this:
//XHR POST
const xhr = new XMLHttpRequest; // creates new object
const url = 'https://api-to-call.com/endpoint';
const data = JSON.stringify({"application": applicationName}); // converts data to a string
xhr.responseType = 'json';
xhr.onreadystatechange = () => {
if(xhr.readyState === XMLHttpRequest.DONE) {
return xhr.response;
}
}
xhr.open('POST', url); // opens request
xhr.send(data); // sends object
you should use promise instead of callback and do something like that.
const url = "https://httpbin.org/post";
const applicationName = "test";
getResponse(url, applicationName)
.then(response => {
//work here, not outside
console.log(response);
})
.catch(error => {
console.log(error);
})
function getResponse(url, applicationName) {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
"application": applicationName
}));
xhr.onload = function() {
// print JSON response
if (xhr.status >= 200 && xhr.status < 300) { // if valid
// work here
const response = JSON.parse(xhr.response.replace(/"/g, '"'));
const data = JSON.parse(response.data.replace(/"/g, '"'));
resolve(data);
}
reject(xhr.response); // reject and return the response if not valid
}
})
}
If you want to learn more about asynchronous https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts, I invite you to go to this website to learn a little more about the promise.
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises
The callback is executed after the code returned xhr.responseText. So that means xhr.responseText returns null.
I would recommend using the fetch API opposed to the older XMLHttpRequest you are using now. The fetch API is basically a Promise based XMLHttpRequest.
Your function would look something like:
async function getResponse( url, applicationName ) {
const json = JSON.stringify({
"application": applicationName
});
return fetch( url, {method: 'POST', headers: { 'Content-Type':'application/json'}, body: json} );
}
// access like this
getResponse( url, applicationName)
.then( response => { console.log(response) });
async function someFunction( url, applicationName ) {
// or pause the code while the request is fetched by using await, note that you need to be in a function that is declared async to use this approach.
const response = await getResponse( url, applicationName );
}
Fetch documentation can be found at MDN: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

How I do use oauth in the reddit api in browser?

Nothing I do works, and I keep getting ridiculous CORS errors and other things. I just want to do a normal oath to log a user in, through the browser. I want to use snoowrap, but I can't even get far enough to use it, because i need a refresh token.
I already authorize the app and get the 'code' back from the API, which im then supposed to use by making a post request to https://www.reddit.com/api/v1/access_token.
But I just get CORS errors every time.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.reddit.com/api/v1/access_token. (Reason: missing token ‘access-control-allow-headers’ in CORS header ‘Access-Control-Allow-Headers’ from CORS preflight channel).
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.reddit.com/api/v1/access_token. (Reason: CORS request did not succeed).
code:
const redirect_uri = 'https://EXAMPLE.com/reddit/';
const client_id = 'xxxxxxxxxxxxx';
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString); /*global URLSearchParams*/
const code = urlParams.get('code');
var snoowrap = window.snoowrap;
if (code) {
console.log('code gotten', code);
const data = {
grant_type: 'authorization_code',
code: code,
redirect_uri: redirect_uri
};
ajax('https://www.reddit.com/api/v1/access_token', data, 'Basic client_id:', result => {
console.log(result);
const r = new snoowrap({
userAgent: 'skeddit',
clientId: client_id,
clientSecret: 'fFP-6BKjFtvYpIkgFGww-c6tPkM',
refreshToken: '',
});
r.getHot().map(post => post.title).then(console.log);
});
}
//GET: ajax(String url, Function success)
//POST: ajax(String url, Object postData, Function success)
function ajax(url, arg2, arg3, arg4) {
if (typeof arg2 == 'function')
var success = arg2;
else {
var postData = arg2;
var headers = arg3;
var success = arg4;
}
console.log('AJAX - STARTING REQUEST', url)
//start new request
var xhttp = new XMLHttpRequest({mozSystem: true});
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
success(JSON.parse(this.response));
xhttp = null;
console.log('AJAX - COMPLETE', this.response);
}
};
if (postData) {
//post request
console.log('post data: ', postData);
var formData = new FormData();
for ( var key in postData ) {
formData.append(key, postData[key]);
}
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("Authorization", headers);
xhttp.send(formData);
}
else {
//get request
xhttp.open("GET", url, true);
xhttp.send();
}
return xhttp;
}
I don't even understand why something would prevent me from doing a POST request to a public api
After hours of searching I found a solution:
If you're creating a browser-only JS app (no server), you should select your app type as "installed app" (instead of "web app") in the reddit console.
Then you have to send an Authorization header whose value is your Client Id, as stated here reddit/wiki/OAuth2
const fd = new FormData();
fd.append("code", code);
fd.append("grant_type", "authorization_code");
fd.append("redirect_uri", "your_redirect_uri");
const r = await fetch("https://www.reddit.com/api/v1/access_token", {
headers: {
Authorization:
"Basic " + btoa(unescape(encodeURIComponent(CLIENT_ID + ":" + ""))),
},
method: "POST",
body: fd,
});

IHttpActionResult won't return JSON object

I'm trying to return a JSON result to my client using IHttpActionResult.
My .Net code, looks like this:
[AllowAnonymous, HttpPost, Route("")]
public IHttpActionResult Login(LoginRequest login)
{
if (login == null)
return BadRequest("No Data Provided");
var loginResponse = CheckUser(login.Username, login.Password);
if(loginResponse != null)
{
return Ok(new
{
message = "Login Success",
token = JwtManager.GenerateToken(login.Username, loginResponse.Roles),
success = true
});
}
return Ok( new
{
message = "Invalid Username/Password",
success = false
});
}
This doesn't work though, as I never seem to see the JSON on the response after my JavaScript fetch:
const fetchData = ( {method="GET", URL, data={}} ) => {
console.log("Calling FetchData with URL " + URL);
var header = {
'Content-Type': "application/json",
}
// If we have a bearer token, add it to the header.
if(typeof window.sessionStorage.accessToken != 'undefined')
{
header['Authorization'] = 'Bearer ' + window.sessionStorage.accessToken
}
var config = {
method: method,
headers: header
};
// I think this adds the data payload to the body, unless it's a get. Not sure what happens with a get.
if(method !== "GET") {
config = Object.assign({}, config, {body: JSON.stringify(data)});
}
// Use the browser api, fetch, to make the call.
return fetch(URL, config)
.then(response => {
console.log(response.body);
return response;
})
.catch(function (e) {
console.log("An error has occured while calling the API. " + e);
});
}
There is no JSON available in the body.
How do I get aresult back to my client to parse? response.body doesn't have the json object.
The console.log shows:
While the request/response shows:
Using striped's advice: console.log(response.json())
I see the message there. It seems to be in the wrong place. Shouldn't it be in the body?
Fetch works like this
Body methods
Each of the methods to access the response body returns a Promise that
will be resolved when the associated data type is ready.
text() - yields the response text as String
json() - yields the result of JSON.parse(responseText)
blob() - yields a Blob
arrayBuffer() - yields an ArrayBuffer
formData() - yields FormData that can be forwarded to another request
I think you need to
return fetch(URL, config)
.then(response => response.json())
.catch(e => console.log("An error has occured while calling the API. " + e));
doc here: https://github.github.io/fetch/
Your are making a GET request but your controller method is expecting a POST request.

Javascript - POST request from server/back-end doesn't work

I am using an API for text-translatation ( you can find it here: Yandex ).
The following piece of code is in the front-end and works fine:
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "myKey/hidden";
var xhr = new XMLHttpRequest(),
textAPI = "fa asta sa fie in engleza";
langAPI = "en";
data = "key="+keyAPI+"&text="+textAPI+"&lang="+langAPI;
xhr.open("POST",url,true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var res = this.responseText;
var json = JSON.parse(res);
if (json.code === 200) {
console.log( json.text[0]);
}
else {
console.log("Error Code: " + json.code);
}
}
};
The console in the browser outputs:
do this to be in English
So it's fine.
However, I need to do this in the back-end. So, I know that XMLHttpRequest is built-in browser, but not in node, therefore I installed it using: npm install xmlhttprequest and I tried to use the same code as I used in the front-end, but I added a log on xhr.onreadystatechange to tell me the status:
xhr.onreadystatechange = function() {
console.log(this.status);
if (this.readyState === 4 && this.status === 200) {
var res = this.responseText;
var json = JSON.parse(res);
if (json.code === 200) {
console.log( json.text[0]);
}
else {
console.log("Error Code: " + json.code);
}
}
};
And what I get is:
0
and
415
As the status.
So it didn't work. I decided to use request instead:
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate";
var keyAPI = "hidden;
var xhr = new XMLHttpRequest();
var textAPI = "fa asta sa fie in engleza";
var langAPI = "en";
request.post({
url: url,
body: JSON.stringify({
key : keyAPI,
text: "tradu",
lang : langAPI
}),
json: true
}, function(err, response, body) {
if(err) {
console.log(err);
return;
}
console.log(body);
});
And the output I get is :
{ code: 415, message: 'Unsupported media type' }
So again, it doesn't work. I also tried adding headers in the post requests, like this:
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
But it made no difference.
I did some digging and found out that status 415 means Unsupported Media Type and I also read some posts/fixes about this but none helped me.
To get it to work, use the form key to send your data (using request)
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate";
var keyAPI = "hidden";
var textAPI = "fa asta sa fie in engleza";
var langAPI = "en";
request.post({
url: url,
form: {
text: textAPI,
key: keyAPI,
lang: langAPI
},
}, function(err, response, body) {
if(err) {
console.log(err);
return;
}
console.log(body);
});

Categories