node.js - 无法将数据从角度发布到节点 api
问题描述
我正在尝试将数据从角度发布到节点 API,数据没有被发布
我已经设置了一个节点 API,在 angular 上设计了一个简单的文本框和按钮,单击时,文本框值应该发布到节点 API,数据没有被发布,也没有来自 angular 订阅方法的响应
安装服务.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import {Observable,Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class InsService {
name: String;
constructor(private http:Http) { }
postAPIData(name: String):Observable<any>{
console.log("hi");
return this.http.post('http://localhost:3000/', {"name":name})
}
}
ins.component.ts
import { Component, OnInit } from '@angular/core';
import {InsService} from '../ins.service'
@Component({
selector: 'app-ins',
templateUrl: './ins.component.html',
styleUrls: ['./ins.component.css']
})
export class InsComponent {
ivalue:String;
ins:InsService;
constructor()
{
}
insoperation(insertion:String)
{
if(insertion)
{
this.ivalue=insertion;
console.log(this.ivalue);
this.postdata();
}
}
postdata()
{
()=>{this.ins.postAPIData(this.ivalue).subscribe((response)=>{
console.log('response from post data is ', response);
})};
}
}
服务器.js
var express=require("express");
var app=express();
var bodyParser = require('body-parser')
var cors = require("cors");
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(3000,"localhost",function(req,res,next){
console.log("Server running on port 3000");
})
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('/',function(req,res,next){
console.log(req.body);
})
我希望数据从角度发布到节点
解决方案
在构造函数中定义服务
constructor(private ins:InsService ) {}
并从中删除参考
ins:InsService; // this line
您需要将角度上的 postdata 方法更改为
(()=>{this.ins.postAPIData(this.ivalue).subscribe((response)=>{
console.log('response from post data is ', response);
})})();
或者
postdata()
{
this.ins.postAPIData(this.ivalue).subscribe((response)=>{
console.log('response from post data is ', response);
});
}
您正在定义一个未执行的箭头函数
推荐阅读
- html - div 显示 flex 文本 alling
- common-lisp - 如何在 Comon Lisp 上交付基于编译配置文件的 lib 项目?
- c# - 并行 ForEach 性能缓慢
- javascript - 如何根据用户选择使用数据库中的数据自动填充字段
- c# - ASP.NET Core - 使用多种身份验证方法
- python - 10 骰子总和与特定数字相比
- laravel-5 - 我如何使用 laravel Cashe 在 10 秒内设置新的 Cashe
- javascript - 如何为 react-bootstrap 组件添加自定义样式?
- reactjs - 在日视图中将大日历悬停在单元格上
- elasticsearch - 具有不存在的嵌套字段或嵌套字段的条件存在的记录集