Error header name must be a valid http token

I had trouble connecting to the pexel site api by the postman and it gives me the same error: Error: Header name must be a valid HTTP token ["Authorization "] I do not know what to do, th...

I had trouble connecting to the pexel site api by the postman and it gives me the same error:

Error: Header name must be a valid HTTP token [«Authorization «]

I do not know what to do, thank you for helping me :)

asked Apr 1, 2021 at 7:19

nafashmn.ir's user avatar

nafashmn.irnafashmn.ir

811 gold badge2 silver badges9 bronze badges

2

There should be an empty line break between the header (content-type: application/json) and the request payload/data.

PATCH http://localhost:5000/users/61b6356454f499270755aee9
content-type: application/json

{
  "first_name": "John"
}

answered Dec 13, 2021 at 0:44

Sathish Arumugam's user avatar

You must put an empty line before your body

Invalid

POST http://localhost:3000/api/report/expense/create HTTP/1.1
Content-Type: application/json
{
    "source": "Business",
    "amount": 200
}

Valid

POST http://localhost:3000/api/report/expense/create HTTP/1.1
Content-Type: application/json

{
    "source": "Business",
    "amount": 200
}

answered Sep 16, 2022 at 14:54

Md Shayon's user avatar

You put your Authorization key in header parameters

{ «Authorization: YOUR_API_KEY» }

find more from here

answered Apr 1, 2021 at 7:41

Anushka's user avatar

AnushkaAnushka

3263 silver badges9 bronze badges

1

You can use http.Client() instead, like this:

class API_Manager {
      Future<Model> getData() async {
        var client = http.Client();
        var Model;
        String url =
            'https://examplelink.com';
        String basicAuth = 'Basic your_auth_key_here';
        try {
          var response = await client.get(url,
              headers: <String, String>{'authorization': basicAuth});
          print(response.statusCode);
          developer.log(response.body); //to get your json data
          if (response.statusCode == 200) {
            var jsonString = response.body;
            var jsonMap = json.decode(jsonString);
            Model = MyModel.fromJson(jsonMap);
          }
        } catch (Exception) {
          return Model;
        }
        return Model;
      }
    }

answered Apr 1, 2021 at 9:06

Shreyas Bhardwaj's user avatar

I found the answer, we have to write this part manually in the headers :)

answered Apr 1, 2021 at 11:27

nafashmn.ir's user avatar

nafashmn.irnafashmn.ir

811 gold badge2 silver badges9 bronze badges

Summary

I got the error
[TypeError: Header name must be a valid HTTP Token [":authority"]]

Simplest Example to Reproduce

var request = require('request');

var options = {
    url: '----',
    headers: {
        ':authority': 'www.site.com',
        ':method': 'GET',
        ':scheme': 'https',
        'referer': 'https://site.com',
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.78 Safari/537.36'
    }
};

function callback(error, response, body) {
    if (!error && response.statusCode === 200) {
        console.log(body);
    }
    if (error) {
        console.log(error);
    }
}

request(options, callback);

Expected Behavior

I want to execute request with «:authority» header

Current Behavior

It doesn’t work.

Possible Solution

Add a flag use raw headers and pass headers as is.

Context

Plain nodejs.

Your Environment

software version
request 2.81.0
node v5.10.1
npm 5.3.0
Operating System mac os 10.12.6

The http.validateHeaderName() (Added in v14.3.0) property is an inbuilt property of the ‘http’ module which performs the low-level validations on the provided name that are done when res.setHeader(name, value) is called. Passing illegal value as the name will result in a TypeError being thrown, identified by code: “ERR_INVALID_HTTP_TOKEN“.

It is not necessary to use this method before passing headers to an HTTP request or response. The HTTP module will automatically validate such headers.

Note: Use the latest version of Node.js to get the required Output.   

In order to get a response and a proper result, we need to import ‘http’ module.

const http = require('http');

Syntax:

http.validateHeaderName(name);

Parameters: This property accepts a single parameter as mentioned above and described below:

  • name <String>: It accepts the name of the header and it is case-insensitive.

Return Value: It does not return any value, instead validates whether the header is acceptable or not.

The below example illustrates the use of http.validateHeaderName() property in Node.js.

Example 1: Filename: index.js

Javascript

var http = require('http');

const { validateHeaderName } = require('http');

try {

  validateHeaderName('');

} catch (err) {

  err instanceof TypeError;

  console.log("Error Occurred", err.code);

  console.log(err.message);

}

Run index.js file using the following command:

node index.js

Output:

In Console 
>> Error Occurred: ‘ERR_INVALID_HTTP_TOKEN’ 
>> Header name must be a valid HTTP token [“”] 
 

Example 2: Filename: index.js

Javascript

var http = require('http');

const { validateHeaderName } = require('http');

const PORT = process.env.PORT || 3000;

var httpServer = http.createServer(

  function(request, response) {

  response.setHeader('Content-Type', 'text/html');

  response.setHeader('Set-Cookie', ['type=ninja',

  'language=javascript']);

  try {

    validateHeaderName('Content-Type');

    console.log("Header 'Content-Type' Validated True...")

    http.validateHeaderName('set-cookie');

    console.log("Header 'set-cookie' Validated True...")

    http.validateHeaderName('alfa-beta');

    console.log("Header 'alfa-beta' Validated True...")

    validateHeaderName('@@wdjhgw');

  } catch (err) {

    err instanceof TypeError;

    console.log("Error Occurred", err.code);

    console.log(err.message);

  }

  const headers = response.getHeaders();

  console.log(headers);

  response.writeHead(200,

    { 'Content-Type': 'text/plain' });

  response.end('ok');

});

httpServer.listen(PORT, () => {

  console.log("Server is running at port 3000...");

});

Run index.js file using the following command:

node index.js

Output:

In Console 
>> Server is running at port 3000… 
Header ‘Content-Type’ Validated True… 
Header ‘set-cookie’ Validated True… 
Header ‘alfa-beta’ Validated True… 
Error Occurred ERR_INVALID_HTTP_TOKEN 
Header name must be a valid HTTP token [“@@wdjhgw”] 
[Object: null prototype] { 
 ‘content-type’: ‘text/html’, 
 ‘set-cookie’: [ ‘type=ninja’, ‘language=javascript’ ] 

 

Now run http://localhost:3000/ in the browser.

Output: In Browser 

ok

Reference: https://nodejs.org/api/http.html#http_http_validateheadername_name

when I’m trying to set the header in the following way ,it’s working absolutely fine.

response.setHeader('Content-Type', 'application/json');

but when I’m trying to add variable instead of exact header name/value in the following way, it’s showing error :-(

response.setHeader(result.headers);

if you console.log(«headers -> » + result.header) the result would be the same.

headers -> 'Content-Type', 'application/json'

following are the exact error I’m getting , not able to figure out how to get around it.

 _http_outgoing.js:487

throw new TypeError(`Header name must be a valid HTTP Token ["${name}"]`);

^



 TypeError: Header name must be a valid HTTP Token ["'Content-Type', 'application/json'"]

at validateHeader (_http_outgoing.js:487:11)

at ServerResponse.setHeader (_http_outgoing.js:498:3)

at C:service-mockersrcmainapp.js:54:22

at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:511:3)

Below is whole code I’m trying to implement :

var http = require('http');

var fs = require('fs');

var path = require('path');

var repl = require('repl');

var map={};

var key;

var value;



//create a server object:

var server = http.createServer(function(request, response) {



    fs.readFile("./resources/FileData1.txt", function(err, data) {

        if(err) throw err;

        content = data.toString().split(/(?:rn|r|n)/g).map(function(line){

            return line.trim();

        }).filter(Boolean)

        var result = processFile(content);

        console.log("url -> " + result.url);

       console.log("status -> " + result.status);

       console.log("headers -> " + result.headers);

       console.log("body -> " + result.body);



       function objToString (obj) {

        var str = '';

        for (var p in obj) {

            if (obj.hasOwnProperty(p)) {

                str +=  obj[p] + 'n';

            }

        }

        return str;

    }

    function processFile(nodes) {



        nodes.forEach(function(node) {

            if(node.startsWith("//")){

                key = node.substring(2, node.length-2).toLowerCase().trim();

                return;    

            }

            else{

                value = node;

            }

            // map[key] = value;

            if(key in map){

                map[key].push(value);

            }else{

                map[key]= [value]; 

            }

        });



        return map;

        // console.log(map);

    }

   if(request.url == result.url ){

        response.setHeader(result.headers);

        // response.setHeader('Content-Type', 'application/json');

        response.write( objToString(result.body) );

        response.statuscode = parseInt( result.status );

        response.end();

    }else {

        // response.writeHead(404, {"Content-Type": "text/html"});

        response.end("No Page Found");

        }

      });

 });


var port = process.env.PORT || 8080;

server.listen(port, function() {

    console.log('Listening on port ' + port);

});

Свойство http.validateHeaderName () (добавлено в v14.3.0) — это встроенное свойство модуля http , которое выполняет низкоуровневые проверки предоставленного имени, которые выполняются при вызове res.setHeader (name, value) . Передача недопустимого значения в качестве имени приведет к возникновению ошибки TypeError , идентифицируемой кодом: « ERR_INVALID_HTTP_TOKEN ».

Нет необходимости использовать этот метод перед передачей заголовков в HTTP- запрос или ответ. Модуль HTTP автоматически проверяет такие заголовки.

Примечание. Используйте последнюю версию Node.js, чтобы получить требуемый результат.

Чтобы получить ответ и правильный результат, нам нужно импортировать модуль http.

 const http = require ('http');

Синтаксис:

http.validateHeaderName(name);

Параметры: это свойство принимает один параметр, как указано выше и описано ниже:

  • name < String > : принимает имя заголовка без учета регистра.

Возвращаемое значение: он не возвращает никакого значения, вместо этого проверяет, приемлем ли заголовок или нет.

В приведенном ниже примере показано использование свойства http.validateHeaderName () в Node.js.

Example 1: Filename: index.js

var http = require("http");

const { validateHeaderName } = require("http");

try {

  validateHeaderName("");

} catch (err) {

  err instanceof TypeError;

  console.log("Error Occured", err.code);

  console.log(err.message); 

}

Запустите файл index.js, используя следующую команду:

 узел index.js

Выход:

In Console
>> Error Occured: ‘ERR_INVALID_HTTP_TOKEN’
>> Header name must be a valid HTTP token [“”]

Example 2: Filename: index.js

var http = require("http");

const { validateHeaderName } = require("http"); 

const PORT = process.env.PORT || 3000;

var httpServer = http.createServer(

  function(request, response) {

  response.setHeader("Content-Type", "text/html");

  response.setHeader("Set-Cookie", ["type=ninja"

  "language=javascript"]);

  try {

    validateHeaderName("Content-Type");

    console.log("Header "Content-Type" Validated True...")

    http.validateHeaderName("set-cookie");

    console.log("Header "set-cookie" Validated True...")

    http.validateHeaderName("alfa-beta");

    console.log("Header "alfa-beta" Validated True...")

    validateHeaderName("@@wdjhgw");

  } catch (err) {

    err instanceof TypeError; 

    console.log("Error Occured", err.code); 

    console.log(err.message); 

  }

  const headers = response.getHeaders();

  console.log(headers);

  response.writeHead(200, 

    { "Content-Type": "text/plain" });

  response.end("ok");

});

httpServer.listen(PORT, () => {

  console.log("Server is runnig at port 3000...");

});

Запустите файл index.js, используя следующую команду:

 узел index.js

Выход:

In Console
>> Server is running at port 3000…
Header ‘Content-Type’ Validated True…
Header ‘set-cookie’ Validated True…
Header ‘alfa-beta’ Validated True…
Error Occured ERR_INVALID_HTTP_TOKEN
Header name must be a valid HTTP token [“@@wdjhgw”]
[Object: null prototype] {
 ‘content-type’: ‘text/html’,
 ‘set-cookie’: [ ‘type=ninja’, ‘language=javascript’ ]
}

Теперь запустите http: // localhost: 3000 / в браузере.

Вывод: в браузере

 Ok

Ссылка: https://nodejs.org/api/http.html#http_http_validateheadername_name

РЕКОМЕНДУЕМЫЕ СТАТЬИ

Андрей Кожемякин

Добрый день. Моё решение в терминале проходит

// removed

Но в тестах сталкиваюсь с ошибкой

request › should work

TypeError [ERR_INVALID_HTTP_TOKEN]: Header name must be a valid HTTP token ["post /upload http/1.1"]

Не могу понять какой валидный http Токен он от меня требует?


1


0

Сергей К.

Андрей, добрый день! Не нужно дополнительно подключаться через telnet.


0

Используйте Хекслет по-максимуму!


  • Задавайте вопросы по уроку

  • Проверяйте знания в квизах

  • Проходите практику прямо в браузере

  • Отслеживайте свой прогресс

Зарегистрируйтесь или
войдите в свой аккаунт

Рекомендуемые программы

Иконка программы Фронтенд-разработчик

Разработка фронтенд-компонентов для веб-приложений



9 февраля



10 месяцев

Иконка программы Онлайн-буткемп. Фронтенд-разработчик

Интенсивное обучение профессии в режиме полного дня



9 февраля



4 месяца

Иконка программы Python-разработчик

Разработка веб-приложений на Django



9 февраля



10 месяцев

Иконка программы Java-разработчик

Разработка приложений на языке Java



9 февраля



10 месяцев

Иконка программы PHP-разработчик

Разработка веб-приложений на Laravel



9 февраля



10 месяцев

Иконка программы Инженер по тестированию

Ручное тестирование веб-приложений



9 февраля



4 месяца

Иконка программы Node.js-разработчик

Разработка бэкенд-компонентов для веб-приложений



9 февраля



10 месяцев

Иконка программы Fullstack-разработчик

Разработка фронтенд- и бэкенд-компонентов для веб-приложений



9 февраля



16 месяцев

Иконка программы Разработчик на Ruby on Rails

Создание веб-приложений со скоростью света



9 февраля



5 месяцев

Иконка программы Верстальщик

Верстка с использованием последних стандартов CSS



в любое время



5 месяцев

Иконка программы Аналитик данных

Профессия

В разработке
с нуля

Сбор, анализ и интерпретация данных



16 марта



8 месяцев

Понравилась статья? Поделить с друзьями:
  • Error hdlcompiler 806
  • Error has occurred in builder routine
  • Error has occurred honkai impact
  • Error has been observed at the following site
  • Error has been encountered while trying to load the file zbrush