【问题标题】:Message received from background. Values reset从后台收到消息。值重置
【发布时间】:2022-02-07 15:19:15
【问题描述】:

我正在从“angular->port 4200”向“expressjs server->port 8000”发送帖子请求。

作为一个例子,我遵循这个例子:https://github.com/kuncevic/angular-httpclient-examples/blob/master/client/src/app/app.component.ts

我收到两个错误:

1)来自 Nodejs 的未定义(数据和 req.body.text)

2) 从后台收到消息。值重置

角边:

  callServer() {
            const culture = this.getLangCookie().split("-")[0];
            const headers = new HttpHeaders()
            headers.set('Authorization', 'my-auth-token')
            headers.set('Content-Type', 'application/json');
            
            this.http.post<string>(`http://127.0.0.1:8000/appculture`, culture, {
              headers: headers
            })
            .subscribe(data => {
            });
        }

expressjs 方面:

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

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.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

app.post('/appculture', function (req, res) {
  var currentCulture = `${req.body.text} from Nodejs`;
  req.body.text = `${req.body.text} from Nodejs`;
  res.send(req.body)
})


app.listen(8000, () => {
    console.log('server started');
})

【问题讨论】:

    标签: node.js angular express


    【解决方案1】:

    要么你没有发送任何在body.text中没有价值的东西

    尝试使用console.log(req.body) 而不是req.body.text

    尝试在客户端console.log(culture)this.getLangCookie() 看看你是否真的在发送一些东西。 您还可以使用浏览器中的网络选项卡来检查您发送的请求。

    【讨论】:

      【解决方案2】:

      角边:

       callServer() {
                  const culture = this.getLangCookie().split("-")[0];
                  const headers = new HttpHeaders()
                  headers.set('Authorization', 'my-auth-token')
                  headers.set('Content-Type', 'application/json');
                  
                  this.http.get(`http://127.0.0.1:8000/appculture?c=` + culture, {
                    headers: headers
                  })
                  .subscribe(data => {
                  });
              }
      

      Nodejs 端:

      app.get('/appculture', function (req, res) {
        currentCulture = req.query.c;
        res.send(req.body)
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-05
        • 1970-01-01
        • 2017-12-29
        • 1970-01-01
        • 1970-01-01
        • 2017-12-04
        • 1970-01-01
        相关资源
        最近更新 更多