M
M
Morrowind2021-05-17 20:35:02
JavaScript
Morrowind, 2021-05-17 20:35:02

How to make a correct simple GET \ POST request in JS with the transfer of a header or other data?

Making a GET\POST request from python to FLASK

r = requests.post('http://127.0.0.1:5001/requestajaxtest', data = {'key':'value'})  
print(r.url)


getting response on server normal on server side using print(request.form.get)

127.0.0.1 - - [17/May/2021 23:29:08] "POST /requestajaxtest HTTP/1.1" 200 -
POST: POST
ImmutableMultiDict([])
<bound method TypeConversionDict.get of ImmutableMultiDict([('key', 'value')])>


If I make a request using JS (selecting one of the functions below):
async function alerttest1() {
    let response = fetch('http://127.0.0.1:5001/requestajaxtest', {
  headers: {
    Authentication: 'secret'
  }
});
    };


async function alerttest2() {
   let user = {
  name: 'John',
  surname: 'Smith'
};

let response = await fetch('http://127.0.0.1:5001/requestajaxtest', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json;charset=utf-8'
  },
  body: JSON.stringify(user)
});

let result = await response.json();
alert(result.message);
 };


RESULT: nothing is transmitted at all. Just empty on the server side.
request.form.get

POST: GET
ImmutableMultiDict([])
<bound method TypeConversionDict.get of ImmutableMultiDict([])>


Either I'm not writing JS requests correctly, or I'm reading js incorrectly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
soremix, 2021-05-17
@hekkaaa

upd: If you send JSON - you need to receive them a little differently, request.formthey will not be in them, it does not accept JSON data. In the case of your queries via python, you were passing in a normal application/x-www-form-urlencoded, for which the c variant request.formis suitable. When you send requests through a JS script, you send them already in a form application/jsonthat can be received request.json
throughrequest.headers.get('Authentication')

did not understand the question
В консоли ошибок нет? Не вижу вызова JS функций, вы их вызываете?
Ну и хотелось бы знать, есть ли во вкладке Network браузера какие-то запросы?
Так же напомню, что фласк по умолчанию работает на порте 5000, у вас же 5001. Надеюсь и фласк вы запустили на нем

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question