简体   繁体   English

post 请求在 Postman 和 cURL 中有效,但在 Angular 中无效

[英]The post request works in Postman and in cURL but not in Angular

I have a remote server and a local client which sends a simple post request with one header Content-Type: application/json and with the body '{"text": "hello"}' .我有一个远程服务器和一个本地客户端,它发送一个简单的 post 请求,其中包含一个标题Content-Type: application/json和正文'{"text": "hello"}'

The server code is here.服务器代码在这里。 It prints the request body and the header.它打印请求正文和标题。

import * as express from 'express';
import * as bodyParser from "body-parser";

const app = express();
const router = express.Router();

router.route("/home")
    .all(bodyParser.json())
    .all(function (req, res, next) {
        console.log(req.body, req.headers['content-type']); // !!! print to console body and header
        next(); 
    })
    .post( (req, res, next) => {
        res.status(200).json({
                    message: req.body,
                })
            }
    );

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "GET, PATCH, PUT, POST, DELETE, OPTIONS");
    next();
});
app.use('/api/v1', router);

app.listen(3000, function(){
    console.log('listening on 3000');
});

The post request works fine from Postman and from curl. Postman 和 curl 的 post 请求工作正常。

curl --location --request POST 'http://vm-gudiea.sio.lab.emc.com:3000/api/v1/home' --header 'Content-Type: application/json' --data-raw '{\"text\": \"hello\"}'

For both requests the server prints the following body and content-type header.对于这两个请求,服务器打印以下正文和content-type标头。

{ text: 'hello' } 'application/json'

But I need to send the request from my Angular app.但我需要从我的 Angular 应用程序发送请求。 I have the following method in a service there我在那里的服务中有以下方法

sendInitialRequest(): void {
    const myHeaders = new HttpHeaders().set('Content-Type', 'application/json');
    this.http.post(this.remoteUrl, JSON.stringify({text: 'hello'}), {headers: myHeaders})
      .subscribe(data => console.log(data));
  }

But if I call the method remote server will print the output但是如果我调用方法远程服务器将打印输出

{} undefined

So it didn't get a Content-Type header and body for some reason.因此,由于某种原因,它没有获得Content-Type标头和正文。 Where is the bug here?这里的错误在哪里? How can I send a post request with body and header from an Angular app ?如何从 Angular 应用程序发送带有正文和标题的 post 请求?

if it is related to cors, install this package in you API https://www.npmjs.com/package/cors如果与 cors 相关,请在您的 API https://www.npmjs.com/package/cors 中安装此包

then use it as following然后按如下方式使用它

import * as cors from 'cors';

...

app.options('*', cors());
app.use(cors());

other tipps:其他提示:

do not stringify your JSON in the angular request.不要在角度请求中将您的 JSON 字符串化。 also there is not need to explicitly set the json header, angular will take care of that for you.也不需要显式设置 json 标头,angular 会为您处理。

this.http.post(this.remoteUrl, {text: 'hello'})
      .subscribe(data => console.log(data));

It seems you have cross-origin error.看来你有跨域错误。 Try this:尝试这个:

npm install --save cors
import express from 'express';
import cors from 'cors';

cosnt app = express();

app.use(cors());
/* your regular routes go here */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Axios 库无法响应 post 请求,尝试使用 curl 和 postman 工作 - Axios library failing to respond for post request, trying with curl and postman works 发布请求在 Postman 中有效,但在 Javascript 中无效 - Post Request Works in Postman But Not in Javascript POST 请求适用于 Postman 但获取失败? - POST Request works with Postman but fails in fetch? 发布请求适用于邮递员,但不适用于javascript提取功能 - Post request works in postman but not in javascript fetch function POST请求在POSTMAN中有效,但在我的代码JS中无效 - POST request works in POSTMAN but not in my code JS POST请求适用于Postman,但不适用于axios或.fetch() - POST request works with Postman, but not with axios or .fetch() POST请求因XMLHttpRequest()而失败,但可与Postman一起使用 - POST request fails with XMLHttpRequest(), yet works with Postman 简单的 POST 请求在 Postman 中有效,但在浏览器中无效 - Simple POST request works in Postman but not in browser 对Flickr API的AJAX请求返回0个结果,但可与curl / postman一起使用 - AJAX request to Flickr API returns 0 results, but works with curl/postman 我的 GET 请求在 POSTMAN 和 Curl 中运行良好,但在 JavaScript 代码中运行良好 - My GET request works fine in POSTMAN and Curl, but not in JavaScript code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM