【问题标题】:How to make post request from angular to node server如何从角度向节点服务器发出发布请求
【发布时间】:2018-01-26 14:16:49
【问题描述】:

当我在节点服务器上打印请求内容时,我无法在任何地方看到用户数据。

这是我的节点服务器:

var http = require('http');
http.createServer( function (request, response) {  
    console.log(request);
}).listen(8080);
console.log('Server running at http://127.0.0.1:8080/');

这里是 Angular2 代码:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Http, Response, Headers , RequestOptions } from "@angular/http";
import 'rxjs/add/operator/retry'; // to be able to retry when error occurs
import { Observable } from "rxjs/Rx";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit{
  title = 'Angular Test';
  user = { id : 1, name : "Hello"};
  constructor (private http: Http) {}

  ngOnInit(): void {
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    console.log(this.user);

    this.http.post("http://localhost:8080/", this.user, options)
    .subscribe( 
    (err) => {
        if(err) console.log(err);
        console.log("Success"); 
    });
  }
}

任何人都可以帮助我或解释如何以角度处理 http 请求。

【问题讨论】:

  • 你在 Node.JS 中使用 express 框架吗?
  • 您的代码中缺少一些东西(例如节点服务器实现、用于发布的路由器、映射和订阅发布调用等)。参考这些链接,将对您有所帮助。 SO1SO2 和这个article
  • 你在 nodejs 中使用 expressjs 吗?
  • @Darshita 我没有在 Node 中使用 express.js。好点了吗?
  • @echonax。不,我不是。是不是更好。

标签: node.js angular http


【解决方案1】:

那是你的服务器:

const express = require('express')
const bodyParser = require('body-parser');
const app = express()

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}) );

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

app.post('/ping', function (req, res) {
  res.send(req.body)
})

app.listen(3000, function () {
  console.log('Example app listening on port 3000!')
})

那是你的 Angular 客户端:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user = { id : 1, name : 'Hello'};

  constructor(private http: HttpClient) { }

  callServer() {
    const headers = new HttpHeaders()
          .set('Authorization', 'my-auth-token')
          .set('Content-Type', 'application/json');

    this.http.post('http://127.0.0.1:3000/ping', JSON.stringify(this.user), {
      headers: headers
    })
    .subscribe(data => {
      console.log(data);
    });
  }
}

回购https://github.com/kuncevic/angular-httpclient-examples

【讨论】:

    【解决方案2】:

    我已经在我们的文档页面中写了这个,但由于它现在已被弃用,我将在此处复制它。

    您的节点部分 app.js 应如下所示(假设您将 expressjs 与 node.js 一起使用):

    app.js:

    var express = require('express');
    var app = express();
    var server = require('http').Server(app);
    var bodyParser = require('body-parser');
    
    server.listen(process.env.PORT || 8080, function(){
        console.log("Server connected. Listening on port: " + (process.env.PORT || 8080));
    });
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: true}) );
    
    app.use( express.static(__dirname + '/front' ) );
    
    app.post('/test', function(req,res){ //**** http request receiver ****
      var myTestVar = "Hello World";
      return res.send(myTestVar);
    });
    
    //send the index.html on every page refresh and let angular handle the routing
    app.get('/*',  function(req, res, next) {
        console.log("Reloading");
        res.sendFile('index.html', { root: __dirname }); 
    });
    

    当您向localhost:8080/test 发布内容时,使用此节点配置,您将在订阅回调中收到myTestVar 作为响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 2021-03-09
      相关资源
      最近更新 更多