【问题标题】:Getting the last Object when fetching from express从快递中获取时获取最后一个对象
【发布时间】:2021-08-10 22:39:00
【问题描述】:

如果这是一个愚蠢的问题,我很抱歉,但我是这个“后端工作”的新手。我在下面有这段代码,问题是每当我调用 fetchSum() 时,数据都会成功发送到服务器,但是当它返回客户端时,它会给我这个错误。 JSON中位置0的意外令牌

NUXT.JS

<script>
export default {
  data() {
    return {
      sumInput: '',
      regInput: 'EUNE',
      summonerSearched: '',
      loadedSummoner: ''
    };
  },
  methods: {
    async fetchSum() {
      fetch('http://localhost:3001', {
        method: 'POST',
        headers: {
          'Content-type': 'application/json; charset=UTF-8'
        },
        body: JSON.stringify({
          summoner: this.sumInput,
          region: this.regInput
        })
      });
      this.loadedSummoner = await fetch('http://localhost:3001/loadedSum', {}).then(t => t.json());
      console.log(this.loadedSummoner.summoner);
    }
  }
};
</script>

和快递

const express = require('express');
const bodyParser = require('body-parser');
const PORT = process.env.PORT || 3001;
const cors = require('cors');

const app = express();

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

let summoner;
app.post('/', async (req, res) => {
  summoner = 
req.body;
  console.log(summoner);
});

app.get('/loadedSum', (req, res) => {
  res.json(summoner);
});

app.listen(PORT, () => {
  console.log('Server is running on port ' + PORT);
});

【问题讨论】:

  • 你为什么在等待 req.body?
  • 我认为没有它,它无法获取数据,因为它没有在那里传递,但这不是问题。

标签: javascript node.js vue.js nuxt.js


【解决方案1】:

问题是您没有等待提交数据的第一次提取。 我希望此代码仅用于测试,因为您不应在全局范围内共享用于请求上下文的数据。

async fetchSum() {
      await fetch('http://localhost:3001', {
        method: 'POST',
        headers: {
          'Content-type': 'application/json; charset=UTF-8'
        },
        body: JSON.stringify({
          summoner: this.sumInput,
          region: this.regInput
        })
      });
      const response = await fetch('http://localhost:3001/loadedSum', {});
      console.log(response.json().summoner);
    }

编辑 您正在全局存储请求,当超过 1 个客户端使用此类 api 时会出现问题。采取以下场景:

  1. 用户 A 调用 Post 并设置召唤者
  2. 用户 B 调用 Post 并设置召唤者
  3. 用户 A 调用 Get 并获得错误的召唤者,因为用户 B 在第 2 步覆盖了它

当您将特定请求数据存储到全局变量时会发生这种情况。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 1970-01-01
    • 2023-03-19
    • 2011-05-18
    相关资源
    最近更新 更多