简体   繁体   English

从快递取货时获取最后一个 Object

[英]Getting the last Object when fetching from express

I'm sorry if this is stupid question, but I'm new to this "backend job".如果这是一个愚蠢的问题,我很抱歉,但我是这个“后端工作”的新手。 I have this code below, and the problem is that whenever i call the fetchSum() the data is succesfuly sent to server, but when it goes back to client it gives me this error.我在下面有这段代码,问题是每当我调用 fetchSum() 时,数据都会成功发送到服务器,但是当它返回客户端时,它会给我这个错误。 Unexpected token < in JSON at position 0 I googled that this happens when the data is none or not ended.意外的令牌 < 在 position 0 的 JSON 中我用谷歌搜索,当数据没有或没有结束时会发生这种情况。 The wierdest think is, that if I fetch it for second time, it returns the 1st value.最奇怪的想法是,如果我第二次获取它,它会返回第一个值。 On 3rd fetch return 2nd etc.第三次取回第二次等。

NUXT.JS 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>

and EXPRESS和快递

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);
});

The problem is that you are not waiting on the first fetch where you submit the data.问题是您没有等待提交数据的第一次提取。 I hope that this code is just for testing as you should not share globally the data meant for request context.我希望此代码仅用于测试,因为您不应全局共享用于请求上下文的数据。

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);
    }

EDIT You are storing the request globally and this has problems when more than 1 client uses such api.编辑您正在全局存储请求,当多个客户端使用此类 api 时会出现问题。 Take following scenario:采取以下场景:

  1. User A calls Post and sets summoner用户 A 调用 Post 并设置召唤者
  2. User B calls Post and sets summoner用户 B 调用 Post 并设置召唤者
  3. User A calls Get and gets the wrong summoner because user B overwrote it at step 2用户 A 调用 Get 并得到错误的召唤者,因为用户 B 在第 2 步覆盖了它

This happen when you store specific request data to global variables.当您将特定请求数据存储到全局变量时会发生这种情况。

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

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