G
G
Galdar Turin2020-06-23 14:26:52
JavaScript
Galdar Turin, 2020-06-23 14:26:52

How to make a POST request, a cry from the heart?

Good afternoon!
I make a request through Angular, the source is installed on a certified server. But it gives this error:

First way

Ошибка:
5ef1e6586186f796763184.png
Код:
var xhr = new XMLHttpRequest();
    xhr.open('POST', 'https://api3.******/');
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');


    xhr.responseType = 'json'

    xhr.onload = () => {
      console.log(xhr.response)
    };

    xhr.send(JSON.stringify({
      "login": "******",
      "pass": "*****"
    }));



Second way

Ошибка:
5ef1e608c7c70103656224.png
Код:
let headers = { headers: new HttpHeaders({'Content-Type': 'application/json; charset=UTF-8'}) }
    let body = new HttpParams()
    body.set("login", "******")
    body.set("pass", "******")



    this.http.post<any>('https://api3.******',
      body,
      headers
    ).subscribe((data)=>{
      console.log(data)
    })



How to solve this problem and get a response from the server? I've already rummaged through the entire Internet. I already found the answer with CROS and without it, and just didn’t try it, but it doesn’t work in Angular. I already think maybe you need to install the library!

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Anton Shvets, 2020-06-23
@Xuxicheta

this.http.post(url, {
  login, password
})

nothing more is needed.
You subscribe, the request is sent, json in the body will be automatic.

A
Alexander, 2020-06-23
@alexmixaylov

Set axios, this is the standard for working with requests
, and what do you have in this.http.post
code, do you send a request like this?

A
Arseny, 2020-06-23
Matytsyn @ArsenyMatytsyn

Zayuzay fetch, look at what gives.
https://developer.mozilla.org/ru/docs/Web/API/Fetc...

D
Denis Shcherbina, 2020-06-24
@Denis_maker

On the client write:

import { HttpClient, HttpHeaders } from '@angular/common/http';

export class Твой_класс {

  headers = new HttpHeaders();
  options = { headers: this.headers, withCredintials: false };

  constructor(private http: HttpClient) {}

  post(data: any) {
    this.http.post('https://........./', data, this.options).subscribe(data => {
       console.log('Ответ сервера: ', data); 
       // Затем смотри, что лежит в data, вероятно просто json поломанный приходит.
       // Проверить ответ на корректность можно здесь: http://json.parser.online
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question