So I want to convert a python script to javascript. The script features a post request, which is supposed to send only a string. I found somewhere that stringname.json() somehow works(which it does), but I am not sure how it works. How do I replicate this in javascript?
Code:
user_info = requests.post('url',
headers=headers,
json = username.json()
Edit: This was a dumb question, ignore this
fetch returns a Promise, so you need to either await it in an async function or use .then
const userInfo = await fetch('url', {
method: "POST",
headers: headers,
body: JSON.stringify(username),
}
Related
I am writing a basic JS function in Microsoft 365 Excel add-in generated using yeoman generator which I just want to fetch some data from a url, while fetching from https it is working fine.
But while doing the same with http I get an error saying TypeError: Failed to fetch. Now, I understand that I can't fetch from a http link but is there a way around.
Have included <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests"> in the html file.
Code
// Fetch json value
console.log(`Fetching`);
var url = "http://1<ip>:<port>/fetch_api";
//var url = "https://api.publicapis.org/entries";
const response = await fetch(url, {
method: 'GET',
headers: {
accept: 'application/json',
},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
console.log(result);
Firstly you made mistype in headers dictionary
headers: { 'Content-Type': 'application/json' }
Then rememeber that this function have to be asynch.
no need to write that much code to get requests using fetch.
get request is the default method. you can write just fetch(URL). for another type of requests you should write method, headers, body, etc.
just write this function and invoke it.
async function getData () {
const URL = 'your_url'
let response = await fetch(URL)
let data = await response.json()
console.log(data)
}
I am using an async await for fetching data. for any type of promise request you should use async await, this will help you to handle promises.
Im somewhat new to this JS async/await functions and im wondering why does it seem to return a different data compared to the jQuery $.ajax() function.
Im developing in Python/Django environment and here is my view which is sending the JSON response
class GetUserToken(APIView):
authentication_classes = [SessionAuthentication, BasicAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request, format=None):
refresh = RefreshToken.for_user(request.user)
content = {
'user': str(request.user), # `django.contrib.auth.User` instance.
'access': str(refresh.access_token),
'refresh': str(refresh),
}
return Response(content)
Here is my JS for getting the data asynchronously. (I combined both just so I can log both output at the same time)
async function get_jwt_token(){
const token = await fetch('/api/user/token/');
return token;
}
$.ajax({
url: '/api/user/token/',
method: 'GET',
success: function(data){
console.log(data);
get_jwt_token().then(function(result){
console.log(result);
}).catch((e) => console.log(e));
},
error: function(xhr, status, err){
console.log(err);
}
});
below is the output
Ajax call output:
{
"user": "admin",
"access": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjMwMDc0ODg5LCJqdGkiOiI5NDAzZjBmMjI0MDU0NzFhODYwYmE4ZGIzNWUwYmI5NyIsInVzZXJfaWQiOjF9.Ee86WDrbiV4Oj2-MyWc3vSIZ5ly2vgbbJflErv-6aN0",
"refresh": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoicmVmcmVzaCIsImV4cCI6MTYzMDEzOTY4OSwianRpIjoiYzVjMjU4ZjM2YzZmNGIxY2FlOGRhODkyZWRhYmRjNDIiLCJ1c2VyX2lkIjoxfQ.sO3e4_6QoidFD5Z6edIrDJidFrKpqFvRt1jljsOL22Q"
}
Async/Await output:
{
type: "basic",
url: "http://localhost:8000/api/user/token/",
redirected: false,
status: 200,
ok: true,
…
}
See image below:
The question is not about converting jquery ajax to JS fetch(), it's about the difference in the response of both function. The selected answer precisely answered the question. For converting jquery ajax to JS fetch(), refer to How to convert Ajax to Fetch API in JavaScript?
In your get_jwt_token() function you need to return token.json().
Explanation from https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
fetch() does not directly return the JSON response body but instead returns a promise that resolves with a Response object.
The Response object, in turn, does not directly contain the actual JSON response body but is instead a representation of the entire HTTP response. So, to extract the JSON body content from the Response object, we use the json() method, which returns a second promise that resolves with the result of parsing the response body text as JSON.
I want to use fetch() to query an API endpoint which powers my search page. It returns a list of search results in JSON format.
I also want to pass to the API the current query submitted by the user. The old implementation used jquery and getJSON. Looking at the docs for getJSON, it says that I can pass in a data variable:
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
Looking at the docs for fetch, I'm not sure how to pass in data as part of my request. So my question is, how do I pass in a string that will be sent to the server along with my request?
EDIT: I think I can append the query to the request URL, like "/search/?q=Something" and send that. Does anyone have a better way?
If you look at the Body section of the documentation on fetch, it lists several types of values you can use to specify the data sent in your request.
Example using FormData:
var fd = new FormData();
fd.append('q', 'Something');
fetch('/search', {
method : "POST",
body : fd
})
.then(...)
Note that you can't use the body option on GET or HEAD requests (which it seems you may be doing in your case). In that situation, you can build up the parameters using URLSearchParams:
var params = new URLSearchParams();
params.append('q', 'Something');
fetch('/search/?' + params.toString(), {
method: 'GET'
})
.then(...);
You can pass as below
fetch('/users', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: 'Hubot',
login: 'hubot',
})
})
I am using mocha to test a promise that is written in a separate javascript file. I am trying to send data to the promise with a POST request, although I'm not sure what the url should be. Here's what I have so far, using request-promise:
var rp = require('request-promise');
var options = {
method: 'POST',
url: '/algorithm.js',
body: data,
json: true // Automatically stringifies the body to JSON
};
rp(options)
.then(function(body){
count++;
done();
});
The error states that I have an invalid url, although I'm not sure how else to POST to promise inside of a javascript file.
I am trying to send data to the promise with a POST request
You can't do that, at least not directly.
POST requests are for sending data to HTTP servers.
Promises are a JavaScript object for handling asynchronous operations.
These are different things.
algorithm.js needs to either contain code that you can call directly, in which case you should require that code and then call the function.
var algorithm = require("algorithm");
if (algorithm.something()) {
count++;
}
done();
… or it should be server side JavaScript that you need to run an HTTP server for. Once you run the HTTP server, you'll be able to use code like what you wrote in the question, but you'll need to provide an absolute URL since you need to say you are using HTTP and localhost and so on.
var options = {
method: 'POST',
url: 'http://localhost:7878/route/to/algorithm',
body: data,
json: true // Automatically stringifies the body to JSON
};
I finally sign up because I have no more idea for my problem.
I use asyncio and aiohttp for my back-end part and javascript for the front-end part. But I stuck with a 405 error. (I precise I am a beginner with theses libraries)
I wish retrieve a json from a post request. Here the javascript function:
function postJson (data){
$.ajax({
url : 'http://localhost:8080/postJson',
type : 'POST',
dataType : 'json',
contentType : 'application/json',
data : data, //data are ready at json format, I do not think I need to use JSON.stringify ? I does not change anything to the error anywhere
success : function(code_html, statut){
console.log("success POST");
},
error : function(resultat, statut, erreur){
console.log("error POST");
}
});
}
and the python code:
async def postJson(request):
data = await request.post()
#some code
return Response()
#asyncio.coroutine
def init(loop):
app = Application(loop=loop)
app.router.add_route('POST', '/postJson', postJson)
handler = app.make_handler()
srv = yield from loop.create_server(handler, '127.0.0.1', 8080)
print("Server started at http://127.0.0.1:8080")
return srv, handler
loop = asyncio.get_event_loop()
srv, handler = loop.run_until_complete(init(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
loop.run_until_complete(handler.finish_connections())
With this code I get a 405 error. Here a bite of what says firebug about the request:
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 // so json is not in the list.
however, if I take back the line contentType : 'application/json' in my javascript file, it works (but the request send a object called MultiDictProxy and I don't understand how to use the function json() from aiohttp.web package (here).
I really need to get a json object. Someone could help me?
I find the solution. I post the conclusion here for people who could be interested:
python side:
replace the line app.router.add_route('POST', '/postJson', postConf) by
app.router.add_route('POST', '/postJson', postConf, expect_handler = aiohttp.web.Request.json)
in the postJson method:
replace data = await request.post() by data = await request.json()
and on javascript side:
data : JSON.stringify(data)
with this, my method works.
Your example works fine except two things:
#asyncio.coroutine and async with are mutually exclusive
postJson() must return response instance, not None