Angular 4 Http POST 不起作用 [英] Angular 4 Http POST not working

查看:26
本文介绍了Angular 4 Http POST 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望每个人都做得很好.我最近开始使用 angular 4.4,我一直在尝试将数据发布到我的 api 服务器,但不幸的是它不起作用.我已经花了大约 2 天的时间,但仍然没有成功.并且已经尝试了 6-7 篇甚至来自 angular.io 的文章.我已经尝试了 HttpHttpclient 模块但似乎没有任何效果.

I hope everyone is doing great. I've recently started working with angular 4.4, i've been trying to post data to my api server, but unfortunately it's not working. I've spent like 2 days on it but still no success. And have already tried 6-7 article even from angular.io. I've tried both Http and Httpclient modules but nothing seems to be working.

问题是,每当我尝试将数据发布到我的服务器时,Angular 都会发出 http OPTIONS 类型的请求,而不是 POST.

The problem is, whenever i try to post data to my server, Angular makes http OPTIONS type request instead of POST.

this.http.post('http://myapiserver.com', {email: 'adam@example.com'}).subscribe(
    res => {
        const response = res.text();
    }
);

而且我也尝试通过请求发送自定义选项,但仍然没有成功.

And i've also tried to send custom options with the request but still no success.

const headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded' });
const options = new RequestOptions({ headers: headers });
options.method = RequestMethod.Post;
options.body = {name: 'Adam Smith'};
//options.body = JSON.stringify({name: 'Adam Smith'}); // i also tried this
//options.body = 'param1=something&param2=somethingelse'; // i also tried this

我使用的是 ASP.NET core 2.0,但由于它不起作用,我也尝试了简单的 php 代码,这是 php 的服务器端代码.而且它也不起作用.

I was using ASP.NET core 2.0, but since it wasn't working i also tried simple php code, Here is the server side code for php. And it's also not working.

<?php
print_r($_POST);
?>

注意:服务器上也启用了 Cors.另外,我还尝试了简单的 get 请求,并且运行良好.

Note: Cors are also enabled on server. Plus I also tried simple get request and its working perfectly fine.

非常感谢您的帮助.

提前致谢

推荐答案

我通过将 Content-Type 设置为 application/x-www-form-urlencoded 解决了这个问题:

I solved it by setting the Content-Type to application/x-www-form-urlencoded:

  const headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
  const options = new RequestOptions({ headers: headers });
  const params = new URLSearchParams();
  params.append('mypostField', 'myFieldValue');
  http.post('myapiendpoint.com', params, options).subscribe();

这篇关于Angular 4 Http POST 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆