【问题标题】:How to send https post request from angular?如何从角度发送 https 发布请求?
【发布时间】:2019-12-04 23:57:09
【问题描述】:

当我尝试在 heroku 上上传图像时,出现此错误: 混合内容:“https://twassol.herokuapp.com/”处的页面通过 HTTPS 加载,但请求了不安全的图像“http://twassol.herokuapp.com/images/%D8%A8%D8%B7%D8%A7%D8%B1%D9%8A%D9%82-1564103914328.jpg”。此内容也应通过 HTTPS 提供。

这个错误: 跨域读取阻塞 (CORB) 阻止了 MIME 类型为 text/html 的跨域响应 http://twassol.herokuapp.com/images/%D8%A8%D8%B7%D8%A7%D8%B1%D9%8A%D9%82-1564103914328.jpg。详情请见https://www.chromestatus.com/feature/5629709824032768

我尝试使用“http://twassol.herokuapp.com/”,它上传图片但不显示。

这是 post.service.ts 文件:

import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Subject } from 'rxjs';
import { map } from 'rxjs/operators';

import { Post } from './post.model';
import { environment } from '../../environments/environment';

const BACKEND_URL =  environment.apiUrl + '/posts/';

@Injectable({providedIn: 'root'})

export class PostsService {
  private posts: Post[] = [];
  private postsUpdated = new Subject<{posts: Post[], postsCount: number}>();

  constructor(private http: HttpClient, private router: Router){}

  getPosts(postsPerPage: number, currentPage: number) {
    const queryParams = `?pagesize=${postsPerPage}&page=${currentPage}`
    this.http.get<{ message: string, posts: any, maxPosts: number }>(BACKEND_URL + queryParams)
      .pipe(map( postData => {
        return { posts :postData.posts.map(post =>{
          return{
            title: post.title,
            content: post.content,
            id: post._id,
            imagePath: post.imagePath,
            creator: post.creator
          }
        }), maxPosts: postData.maxPosts};
      }))
      .subscribe((transformedPostData) => {
        this.posts = transformedPostData.posts;
        this.postsUpdated.next({posts: [...this.posts], postsCount: transformedPostData.maxPosts});
    });
  }
  getPostUpdateListener(){
    return this.postsUpdated.asObservable()
  }

  getPost(id: string){
    return  this.http.get<{_id: string, title: string, content: string, imagePath: string, creator: string}>(
      BACKEND_URL + id
    );
  }

  addPost(title: string, content: string, image: File){
    const postData = new FormData;
    postData.append('title', title);
    postData.append('content', content);
    postData.append('image', image, title);
    this.http.post<{message: string, post: Post}>(BACKEND_URL, postData)
      .subscribe( responseData => {
        this.router.navigate(['/']);
      });
  }

  updatePost(id: string, title: string, content: string, image: string | File){
    let postData: Post | FormData;
    if (typeof(image) === 'object'){
      postData = new FormData;
      postData.append('id', id);
      postData.append('title', title);
      postData.append('content', content);
      postData.append('image', image, title);
    } else {
      postData = {
        id: id,
        title: title,
        content: content,
        imagePath: image,
        creator: null
      }
    }

    this.http
      .put(BACKEND_URL + id, postData)
      .subscribe(response => {
        this.router.navigate(['/']);
      });
  }

  deletePost(postId: string){
    return this.http.delete(BACKEND_URL + postId)
  }
}

【问题讨论】:

标签: node.js angular mongodb express


【解决方案1】:

将您的图像转换为 base64 字符串并在发布请求中传递它

html:

 <button type="button" (click)="upload.click()" >
 <span>Upload Photo</span>
 </button>
 <input #upload formControlName="imageData" type="file" name="imageData" accept='image/*'  (change)="getFiles($event)"style="display:none;">

ts:

      getFiles(event) {
    this.files = event.target.files;
    var reader = new FileReader();
    reader.onload = this._handleReaderLoaded.bind(this);
    reader.readAsBinaryString(this.files[0]);
}

_handleReaderLoaded(readerEvt) {
    var binaryString = readerEvt.target.result;
    this.base64DataOfImage= btoa(binaryString); 
    this.{{your Model}}.imageData = this.base64DataOfImage
    this.fileSrc = 'data:image/png;base64,'+this.base64DataOfImage;
}

从服务中取回数据

html

<img  height="200" [src]="fileSrc" />

ts

//service call(assuming the returned as {"imageData":"base64data"})

this.fileSrc='data:image/png;base64,'+responce.imageData;

确保在后端增加请求正文的大小

app.use(bodyParser.json({limit: "50mb"}));
app.use(bodyParser.urlencoded({limit: "50mb", extended: true, parameterLimit:50000}));

【讨论】:

  • 感谢您的回答,我已经解决了这个问题。这是图像路径的问题,因为我想直接在 heroku 上上传图像,这是不可能的,我必须在 cloudinary 上上传图像并修改我的代码以使用 cloudinary api
  • 如果您只想上传图片,请尝试我的解决方案。您不必再为 cloudinary 付费
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 2021-12-01
相关资源
最近更新 更多