简体   繁体   English

如何从请求响应中获取单个值

[英]How to get single value from request response

I started writing a program that will automate user actions, by now it's meant to be an easier menu to make faster actions by just sending requests to the official website by clicks on my own page.我开始编写一个自动执行用户操作的程序,现在它意味着通过点击我自己的页面将请求发送到官方网站,它是一个更简单的菜单,可以更快地执行操作。 (something like web-bot but not exactly). (有点像网络机器人,但不完全是)。 My problem is when i send login request in response i get back user_id, server, session_id etc. And I need to save that session_id to make the other actions.我的问题是当我发送登录请求作为响应时,我会返回 user_id、server、 session_id等。我需要保存该 session_id 以进行其他操作。 How can i save this to variable.我怎样才能将它保存到变量中。 All in JavaScript.全部在 JavaScript 中。

I was looking in the internet since yesterday for an answer and i still can't find (or understand) how to get this I tried function login(){ fetch('url', { method: 'POST', headers: { //headers }, body: //my Id's }) })我从昨天开始在网上寻找答案,但我仍然找不到(或理解)如何得到这个我试过function login(){ fetch('url', { method: 'POST', headers: { //headers }, body: //my Id's }) })

//There's the problem to solve .then(res => res.text()) .then(data => obj = data) .then(() => console.log(obj)) console.log(body.session_id); //有问题要解决.then(res => res.text()) .then(data => obj = data) .then(() => console.log(obj)) console.log(body.session_id);

// I even tried the substring but 1. It won't work as I want because There are sometimes //more and less letters. // 我什至尝试了子字符串,但是 1。它不会像我想要的那样工作,因为有时//更多和更少的字母。 2. I get and error "Cannot read properties of undefined (reading //'substr')" 2. 我得到错误“无法读取未定义的属性(读取//'substr')”

`session = obj;
session_id = session.substring(291,30)
console.log(session_id)`

It looks like you're using the text() method on the Response object returned from fetch() , which will give you a string representation of the response.看起来您正在对从fetch()返回的Response对象使用text()方法,这将为您提供响应的字符串表示形式。

You probably want to be using the json() method instead, and from that you can get your session_id .您可能希望改用json()方法,并从中获取session_id

This guide has some more useful information that may help you: https://javascript.info/fetch本指南有一些更有用的信息可以帮助您: https ://javascript.info/fetch

Ok it works now with好的,现在可以使用

`async function login(){ let session = await fetch('url', {
    //code
}
let result = await session.json();
console.log(result);
session_id = result.data.user.session_id;
user_id = result.data.user.id;`

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

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