Express无法从背面读取未定义的属性'name'

问题描述 投票:3回答:4

我尝试使用node js和angular(material ui)开发一个全栈应用程序。

我在以下问题上阻止问题。

我正在制作一个小型Web资源管理应用程序。我目前处于Mysql数据库中数据的注册和发送阶段。

我收到以下错误:

TypeError:无法读取未定义的属性'名称'

这是我的代码:

const express = require('express');
const app = express();
var cors = require('cors');
var mysql      = require('mysql');
const body = require("body-parser");

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'totale',
});

app.use(cors());

app.get('/', function (req, res) {
  res.send('Hello World!');
  console.log(req);
});

app.get("/inscription",(req,res)=>{
  var nom = req.body.name;
  var prenom = req.body.prenom;
  var mail = req.body.email;
  var password = req.body.password;
  connection.connect();
  connection.query('INNSERT INTO inscription set nom = ?, prenom = ? ,mail = ? ,password = ? ',[nom,prenom,mail,password],function(err, rows) {
    if (err) throw err;
    console.log('The solution is: ', rows[0].solution);
    });
  //res.send('iok');
  //connection.end();
});


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

这是我的代码:打字稿

import { Component, OnInit } from '@angular/core';
import { FormControl, Validators } from '@angular/forms';
import { User } from './../User';
import { Router } from '@angular/router';
import { FormBuilder, FormGroup } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import {tap} from 'rxjs/operators';


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

export class InscriptionComponent implements OnInit {
  signupForm;
  results;
  //email = new FormControl('', [Validators.required, Validators.email]);

  constructor (private http: HttpClient, private formBuilder: FormBuilder)
  {}
  ngOnInit() {
    this.signupForm = this.formBuilder.group({
      email:"",
      name: "",
      lastname: "",
      password : "",
    });
  }
  public onFormSubmit() {

    const configUrl = 'http://localhost:3000/inscription';

    this.http.post(configUrl,this.signupForm.value)
    .pipe(
      tap(
        data => console.log(configUrl, data),
        error => console.log(configUrl, error)
      )
    )
    .subscribe(results => this.results = results);
 }
}
node.js angular typescript express angular-material
4个回答
1
投票

您需要使用主体解析器,以便可以获取主体对象

app.use(cors());
app.use(express.json()); //Used to parse JSON bodies 👉 Express 4.16+

并且您需要使用post方法

app.post("/inscription",(req,res)=>{
 ...
}

有关此here 🚀的更多信息


1
投票

您必须更改

app.get("/inscription",(req,res)=>{

收件人

app.post("/inscription",(req,res)=>{

1
投票

您必须添加

app.use(body.urlencoded({ extended: false }));
app.use(body.json());

[C0之后]


0
投票

可以,但是我不明白为什么这次我不调理表单数据app.use(cors());

enter image description here
© www.soinside.com 2019 - 2024. All rights reserved.