angular13发送http请求

服务端用的是 express

server.js

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.header("Access-Control-Allow-Origin", "*") // 允许跨域
  console.log(req.query) // 请求数据
  res.send('Hello World!') // 响应数据
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

测试过了 http://localhost:3000 启动正常

PS D:\WorkSpace\Transfer\Angular\HttpRequest\server> node server.js
Example app listening at http://localhost:3000

这是 angular 代码

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

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {

  private url = 'http://localhost:3000?bookName=Java';

  getRequest(): Observable<string> {
    alert('发送请求')
    return this.http.get<string>(this.url)
  }

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    console.log(this.getRequest())
  }

}

现在的问题是, 不管服务端是打开状态, 还是关闭状态, 都请求不到服务端

服务端也接收不到数据

也没有报错

下面是测试图

阅读 2.7k
1 个回答

已解决, 写了一个DemoNote

Angular 向服务端发送 Http 请求

准备工作

ng generate component simple

app.component.html

<app-simple></app-simple>

server.js

const express = require('express')
const app = express()
const port = 3000

app.get('/book/get', (req, res) => {
  // 允许跨域请求
  res.header('Access-Control-Allow-Origin', '*')
  // 获取请求数据
  const bookId = req.query.bookId
  // 响应数据
  res.send({
    id: bookId,
    title: 'Java',
    price: 50.0
  })
})
// -> http://localhost:3000/book/get?bookId=123 -> {"id":"123","title":"Java","price":50}

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

最简单的 Http 请求

模块引入

app.module.ts -> @Append

import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    HttpClientModule,
    BrowserModule
  ]
})

simple.component.ts -> @Append

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

export class SimpleComponent implements OnInit {

  constructor(private http: HttpClient) { }

}

编写测试方法

simple.component.ts -> @Append

export class SimpleComponent implements OnInit {

  // 最简单的Http请求
  demo1(): void {
    const url = 'http://localhost:3000/book/get?bookId=123'
    this.http.get(url).subscribe(response => {
      console.log(response)
    })
  }

  constructor(private http: HttpClient) { }

  ngOnInit(): void {
    this.demo1()
  }

}

运行

启动 server.js

PS D:\WorkSpace\Transfer\Angular\HttpRequest\server> node server.js
Example app listening at http://localhost:3000

启动 angular

ng serve --open

访问 http://localhost:4200

客户端控制台输出如下

{id: '123', title: 'Java', price: 50}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进