Как включить выборку POST в расширении Chrome contentScript? - PullRequest
0 голосов
/ 21 ноября 2018

Я пытаюсь вызвать REST API в расширении Chrome.Мне удалось заставить работать GET, но я не смог заставить работать POST.Тело на стороне сервера всегда пусто.Вот мой запрос на выборку:

  let url = "http://localhost:3000/api/save/one"
  fetch(url, { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json; charset=utf-8" }, mode: "no-cors", body: JSON.stringify(json) })
  .then(resp => console.log(resp))

Когда я исследовал запрос на сервере, я заметил, что тип содержимого на сервере всегда "text / plain; charset = UTF-8".Таким образом, мои заголовки, кажется, не переданы.Тем не менее, заголовок «Принять» прошел.

Это заголовки на сервере:

accept:"application/json"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"

Если я удалю «Принять» из заголовков выборки, я получу это на сервере:

accept:"*/*"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"

Есть объяснение этому?Итак, как заставить работать POST?

1 Ответ

0 голосов
/ 10 апреля 2019

Вам необходимо написать код для метода записи

Слушатель

background.js:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {    
    if (request.contentScriptQuery == "getdata") {
        var url = request.url;
        fetch(url)
            .then(response => response.text())
            .then(response => sendResponse(response))
            .catch()
        return true;
    }
    if (request.contentScriptQuery == "postData") {
        fetch(request.url, {
            method: 'POST',
            headers: {
                'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            },
            body: 'result=' + request.data
        })
            .then(response => response.json())
            .then(response => sendResponse(response))
            .catch(error => console.log('Error:', error));
        return true;
    }
});

Звонящий

Content_script.js

chrome.runtime.sendMessage(
    {
        contentScriptQuery: "postData"
        , data: JSONdata
        , url: ApiUrl
    }, function (response) {
        debugger;
        if (response != undefined && response != "") {
            callback(response);
        }
        else {
            debugger;
            callback(null);
        }
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...