简体   繁体   English

无法获取/Node js

[英]Cannot get / Node js

I'm trying to start serving some static web pages using connect like this:我正在尝试使用如下连接开始提供一些 static web 页面:

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

const app = express();
const port = 3000;

app.use(bodyParser.text());
app.use(cors());

app.post('/api/pesan', (req, res) => {
    console.log(req.body);
    res.status(200).send();
})

app.listen(port, () => console.log('Aplikasi berjalan di port', port));

and this is my app.component.ts这是我的 app.component.ts

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

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

  constructor (private http: HttpClient){}

  kirim(){
    console.log(this.pesan);
    this.http.post('http://localhost:3000/api/pesan', this.pesan).toPromise();
    }

 )

i make newfolder /backend and put server.js there.我创建新文件夹 /backend 并将 server.js 放在那里。 i want to connect the node with app.component.html but i get this ERROR我想将节点与 app.component.html 连接,但我收到此错误

From what I gather, there are two things you want to do:据我所知,你想做两件事:

  1. Create an API and return the data you have posted.创建一个 API 并返回您发布的数据。
  2. Call that API endpoint from your frontend and console.log(...) the data从您的前端调用 API 端点和console.log(...)数据

Here's an updated code that should work and why it didn't work before:这是一个应该可以工作的更新代码,以及为什么它以前不能工作:

Node Server节点服务器

I simply returned the data我只是返回了数据

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

const app = express();
const port = 3000;

app.use(bodyParser.text());
app.use(cors());

app.post('/api/pesan', (req, res) => {
    console.log(req.body);
    // UPDATED: This time, we return the data you passed
    res.status(200).send(req.body);
})

app.listen(port, () => console.log('Aplikasi berjalan di port', port));

Angular App Angular 应用

You were actually able to properly call your endpoint BUT you didn't do anything with the promise you created with .toPromise() .您实际上能够正确调用您的端点,但是您没有对使用.toPromise()创建的 promise 做任何事情。 I updated the code to handle that.我更新了代码来处理它。

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  pesan = { foo: 'some awesome data' };

  constructor (private http: HttpClient){}

  kirim(){
    this.http.post('http://localhost:3000/api/pesan', this.pesan)
       .toPromise()
       .then(response => { 
          const data = response.json();
          console.log(data); 
       });
  }

}

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM