角度发布表格数据(文本输入)到休息API

时间:2018-02-08 12:21:50

标签: javascript angular rest typescript express

我正在尝试将数据(文本输入)从被动表单发布到本地express.js服务器上的REST API。姓名,电子邮件......只是基本的文字输入字段。

这里我将值从Form发送到服务(Form.Component.ts)

  onSubmit(formDirective) 
 {
  this.personservice.senddata(this.personForm.value).subscribe(data=>{
  console.log(data);
  })
 }

在服务中我将数据发布到REST API

constructor(private http: HttpClient) 
  {
    console.log('init PS')
  }

  getPeople(): Observable<People[]> 
  {
    return this.http
      .get<People[]>(this._peopleURL)
      .map( (data: any) => data.people);
  }

  private _peopleURL = "http://localhost:8080/api/people";

  senddata(data : any) 
  {
  var body = JSON.stringify(data);
         var headers = new Headers();
         headers.append('Content-Type', 'application/json');
         return this.http.post(this._peopleURL, data);
  }

控制台日志显示正确的数据,但不会将数据发布到REST API。 enter image description here

我错过了哪些步骤?

编辑:

Here is the code for my express.js server

const express = require('express');

const app = express();

const cors = require('cors')

var corsOptions = {
    origin: 'http://localhost:4200',
    optionsSuccessStatus: 200 
  }

  app.use(function (req, res, next) {

    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:4200');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.use(cors(corsOptions))

app.listen(8080, () => {
    console.log('Server gestartet');
});


app.route('/api/people').get((req, res) => {
    res.send({
      people: [
      { vorname: 'max', nachname: 'müller', email: 'testmail@gmail.com', status: 'true', activity: 'Office' }, 
      { vorname: 'jeremy', nachname: 'püringer', email: 'jp@gmail.com', status: 'true', activity: 'Office' },
      { vorname: 'peter', nachname: 'schmidt', email: 'ps@bluwin.ch', status: 'false', activity: 'service' }
    ]
    });
  });

app.route('/api/people/:vorname').get((req, res) => {
    const requestedPersonSurname = req.params['vorname'];
    res.send({ vorname: requestedPersonSurname });
  });

app.route('/api/save').get()


  const bodyParser = require('body-parser');
  app.use(bodyParser.json());
  app.route('/api/people').post((req, res) => {
    res.send(201, req.body);
  });

1 个答案:

答案 0 :(得分:1)

试试这个。

 senddata(data: any) {
    var body = JSON.stringify(data);
    let headers = new HttpHeaders();
    headers = headers.set('Content-Type', 'application/json; charset=utf-8');;
    return this.http.post(this._peopleURL, data);
  }
  

请注意,我们通过链接连续的set()方法来构建HTTPHeaders对象。这是因为HTTPHeaders是不可变的,其API方法不会导致对象变异。相反,对set的调用将返回一个包含新值属性的新HTTPHeaders对象。

<强> WORKING DEMO