HTTP-запрос JSONP дает 404 в Angular - PullRequest
1 голос
/ 29 мая 2020

Я работал с интеграцией mailchimp в приложение angular, и для его использования в чистом JS я получил код из встроенной формы на сайте mailchimp и следующий код:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<!-- Begin Mailchimp Signup Form -->
<link href="//cdn-images.mailchimp.com/embedcode/classic-10_7.css" rel="stylesheet" type="text/css">
<style type="text/css">
	#mc_embed_signup{background:#fff; clear:left; font:14px Helvetica,Arial,sans-serif; }
	/* Add your own Mailchimp form style overrides in your site stylesheet or in this style block.
	   We recommend moving this block and the preceding CSS link to the HEAD of your HTML file. */
</style>
<div id="mc_embed_signup">
<form action="https://gmail.us10.list-manage.com/subscribe/post?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <div id="mc_embed_signup_scroll">
	<h2>Subscribe</h2>
<div class="indicates-required"><span class="asterisk">*</span> indicates required</div>
<div class="mc-field-group">
	<label for="mce-EMAIL">Email Address  <span class="asterisk">*</span>
</label>
	<input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
</div>
</div>
    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_aaa7182511d7bd278fb9d510d_01681f1b55" tabindex="-1" value=""></div>
    <div class="clear"><input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="button"></div>
    </div>
</form>
</div>
<script type='text/javascript' src='//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js'></script><script type='text/javascript'>(function($) {window.fnames = new Array(); window.ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='ADDRESS';ftypes[3]='address';fnames[4]='PHONE';ftypes[4]='phone';fnames[5]='BIRTHDAY';ftypes[5]='birthday';}(jQuery));var $mcj = jQuery.noConflict(true);</script>
<!--End mc_embed_signup-->

Приведенный выше код работает нормально и без проблем .. То же самое необходимо включить в приложение angular, для которого я пытаюсь сделать следующее:

Ссылка Я взял: https://gist.github.com/inorganik/846c52550db97454646054270e4f1270

И вот реализация,

app.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { HttpClient, HttpParams } from '@angular/common/http';

interface MailChimpResponse {
  result: string;
  msg: string;
}

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
submitted = false;
  mailChimpEndpoint =
    'https://gmail.us10.list-manage.com/subscribe/post?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55';
  error = '';

  constructor(private http: HttpClient) {}

  userForm: FormGroup;

  ngOnInit(): void {
    this.userForm = new FormGroup({
      email: new FormControl('', [
           Validators.required,
            Validators.email,
        ]),
    });
  }

  subscribeEmail() {
    this.error = '';


        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'callback').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }
}

Здесь работает Stackblitz ..

Мое требование - приведенный выше код, который работает во фрагменте, не работает в приложении angular и это приводит к ошибке 404 ..

Пожалуйста, посмотрите на вкладку сети / консоли в инструменте разработчика, которая дает 404 ..

Также я мог заметить, что параметр который я передаю на URL-адрес, не отражается в параметрах запроса сетевого вызова.

Пожалуйста, помогите мне реализовать тот же URL-адрес API, который работает при нажатии кнопки подписки для работы в приложении angular как ну.

Взгляните, пожалуйста, на stackblitz: https://stackblitz.com/edit/angular-jsonp-gfzdr1

1 Ответ

1 голос
/ 29 мая 2020

Вы неправильно отправляете параметры. Вот рабочий пример, который отправит запрос. Он по-прежнему возвращает ошибку, но это ответ MailChimp о том, что вы обработали слишком много записей.

Рабочая версия: https://stackblitz.com/edit/angular-jsonp-1qquhy

...