【问题标题】:sending JSON to Express将 JSON 发送到 Express
【发布时间】:2018-03-16 12:22:12
【问题描述】:

我阅读了很多关于如何通过邮件发送 json 来表达的帖子,但没有一个有效或解决了我的问题。

我的问题是,当阅读req.body 时,req 是请求对象 我得到这样的输出:{ '{"z":"z"}': '' } 我发送了这个对象 {z:"z"}

这是意料之外的,之前也没有看到任何行为。

这是角度 httpClient 请求:

return new Promise((res,rej)=>{
        this.http.post("http://localhost:3000/Auth/Login",{z:"z"},{headers:new HttpHeaders('Content-Type:application/x-www-form-urlencoded')})
            .toPromise()
              .then(
              response =>{
               res(response)
              }
              ).catch(
                  err=>{
                      rej(err)
                  }
              )
    })

这是服务器代码:

router.route('/Login').all(function (req, res, next) {
    next();
}).post(function(req, res, next) {
    console.log(req.body);})

我想要的是获得与我发送的相同的对象。

帮助!

【问题讨论】:

  • 你试过'Content-Type:application/json'
  • 这会创建一个 OPTIONS 请求( preflight request )并且它没有得到很好的响应并且请求失败。我有 chrome 扩展,但没有做任何事情
  • 你可以试试邮递员的同样的api吗?
  • 我确实试过了,当我使用 x-www-form-urlencoded 但不使用 raw 发送时效果很好:{z:"z"} 这是我想要发送的内容
  • 在raw的情况下你改成json了吗?

标签: javascript node.js angular express


【解决方案1】:

在服务中(或使用 api 连接的地方)使用来自@angular/common/httpHttpClient - 因为只有在HttpClient 中才能使用HttpHeaders

简单服务示例:

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

@Injectable()
export class AppService {

  constructor(private http: HttpClient) { }

  toparams = function ObjecttoParams(obj) {
    var p = [];
    for (var key in obj) {
      p.push(key + '=' + encodeURIComponent(obj[key]));
    }
    return p.join('&');
  };

  login(): any {
    return new Promise((res, rej) => {
      let obj = { z: "z" };
      this.http.post("http://localhost:3000/Login", this.toparams(obj), {headers:new HttpHeaders('Content-Type:application/x-www-form-urlencoded')})
        .toPromise()
        .then( response => {
            res(response)
          }
        ).catch(err => {
            rej(err)
          }
        )
    })
  };
}

在模块中:

import { HttpModule } from "@angular/http"
...
imports: [
  ....
  HttpModule
],

Node.js + express 示例:

var express = require('express');
var app = express()
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies

app.all("/*", function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, X-Auth");
    res.header("Access-Control-Allow-Methods", "GET, PUT, POST");
    return next();
});

app.route('/Login').all(function(req, res, next) {
    next();
}).post(function(req, res, next) {
    console.log(req.body);
    res.json(req.body)
});

app.listen(3000)

现在,当您发送 { z: "z" } 时,api 将返回相同的对象,他不会将其解析为 JSON。

获取JSON不是更容易吗?

【讨论】:

  • 它有效,但这不只是儿子解析参数的一种解决方法吗?
猜你喜欢
  • 2017-01-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 1970-01-01
  • 2021-10-07
  • 1970-01-01
相关资源
最近更新 更多