Dolphin
Dolphin

Reputation: 38731

why my fetch body always return null in Google Chrome Extension

Now I am write a Google Chrome Extension code like this:

const apiUrl = defaultConfig.cruiseApi;
        const baseUrl = apiUrl + "/post/sub/source/add-by-plugin/";
        const urlParams ={
            subUrl:rssUrl
        }; 
        fetch(baseUrl,{
            method: 'POST',
            headers:{
                "Content-type": "application/json",
                "token": result.cruiseToken
            },
            body:JSON.stringify(urlParams)
        })
        .then(res => {
            console.info("the result is:"+ JSON.stringify(res.body));
            
        })
        .catch(error =>{
            console.error(error);
        });

but the result body always get {}. this is my api result text:

costTime: "0"
ipAddress: null
msg: "login invalid"
result: null
resultCode: "200"
statusCode: "904"
validationErrors: null

what should I do to parse the http response context successfully? This is the curl command of http request:

curl 'https://api.poemhub.top/post/sub/source/add-by-plugin/' \
  -H 'Connection: keep-alive' \
  -H 'Pragma: no-cache' \
  -H 'Cache-Control: no-cache' \
  -H 'sec-ch-ua: "Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"' \
  -H 'DNT: 1' \
  -H 'sec-ch-ua-mobile: ?0' \
  -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36' \
  -H 'token: eyJ1c2VyX2lkIjoiNyJ9.657a56c26b4a3bbcaaa15a8afb46dc4e3c274f1e161823887960745d9f' \
  -H 'Content-type: application/json' \
  -H 'Accept: */*' \
  -H 'Origin: chrome-extension://jdnjeciaeelnmklhhcpihfekghplaiad' \
  -H 'Sec-Fetch-Site: none' \
  -H 'Sec-Fetch-Mode: cors' \
  -H 'Sec-Fetch-Dest: empty' \
  -H 'Accept-Language: en,zh-CN;q=0.9,zh;q=0.8,zh-TW;q=0.7,fr;q=0.6' \
  --data-raw '{"subUrl":"http://gerry.lamost.org/blog/?feed=rss2"}' \
  --compressed

Upvotes: 0

Views: 426

Answers (1)

Dolphin
Dolphin

Reputation: 38731

invoke json function before use it:

const apiUrl = defaultConfig.cruiseApi;
        const baseUrl = apiUrl + "/post/sub/source/add-by-plugin/";
        const urlParams ={
            subUrl:rssUrl
        }; 
        fetch(baseUrl,{
            method: 'POST',
            headers:{
                "Content-type": "application/json",
                "token": result.cruiseToken
            },
            body:JSON.stringify(urlParams)
        })
        .then(res => {
           return res.json()
        })
        .then(res => {
            console.info("the result is:"+ JSON.stringify(res.body));
            
        })
        .catch(error =>{
            console.error(error);
        });

Upvotes: 1

Related Questions