Is not a function ошибка json

order plays a very big role in app.get('/',(req,res)=>{ });

you can change the name instead of req and res but the second arg should be of res and the first should be of req

like app.get('/',(a,b)=>{ b.json({});

above syntax is res.json({}) ,we are sending a json file at '/'

const express = require('express');
const path = require("path");
const bodyParser = require('body-parser');
const app = express();
const PORT = 80;

app.use(bodyParser.urlencoded({
    extended: false
}));

app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname + "/index.html"));
});

app.post('/api/v1', (req, res) => {
    // const userName=req.body.name;
    res.send("<h1>done</h1>");
    console.log(req.body);
});

app.get("/api/v1/userdata", (req, res) => {
    res.json({
        name: "your_Name",
        email: "your_Email",
        password: "hexed",
    });
});

app.listen(PORT, () => {
    console.log("listening on port 80");
});

Cover image for Dealing with ".json() is not a function" Error

You finished a tutorial about REST API, Ajax, or Fetch and now you’re ready to build a new project using API. Cool! You opened a new file in text editor and start typing away until you encounter a problem. When you write .json(), you will get the «.json() is not a function» error.

You could get around by changing it to .text(), however doing this will make it hard to retrieve data you want from API even though it’s technically responding. What should you do?

The solution? Use items.

Let me give you a quick example where I used it in my book finder project.

I created a function where it will fetch a data from Google Books API and display the search results in HTML. I simplified the codes just to demonstrated the point.

function searchBook() {
  const query = document.querySelector('#search-input').value;
  fetch(`https://www.googleapis.com/books/v1/volumes?q=${query}`)
      .then((res) => res.json())
      .then((data) => {
        let output = '<h2>Search results</h2>';
        data.forEach(book => {
        // Display search results
      })
  }

Enter fullscreen mode

Exit fullscreen mode

This code will not work because there is something missing and prevents the data parameters from being accessed . However, if I add items between data and forEach(), it will work:

function searchBook() {
  const query = document.querySelector('#search-input').value;
  fetch(`https://www.googleapis.com/books/v1/volumes?q=${query}`)
      .then((res) => res.json())
      .then((data) => {
        let output = '<h2>Search results</h2>';
        data.items.forEach(book => {
        // Display search results
      })
  }

Enter fullscreen mode

Exit fullscreen mode

Why this happens? To be honest, I still don’t fully understand why it works this way either, so I’d be happy if any of you provide a better explanation in the comments below. For the time being, here’s my thoughts:

Firstly, It could be the API itself — Not all APIs will work immediately if you simply put .json() and hoped for the best. Some APIs like JSONPlaceholder will work just fine without including items, while others like Google Books API will require to include it to make it work.

Secondly, the API data will be returned in JSON format and since the objects are wrapped inside the array, you will need to get into the array first before you can access the JSON data from which you can then change it into object using the .json().

So there you go! Next time when that error appears again, you know what you’re gonna do.

Время на прочтение
5 мин

Количество просмотров 397K

JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!

Ниже представлен список странных ошибок в JavaScript. Разные браузеры могут выдавать разные сообщения об одинаковых ошибках, поэтому приведено несколько примеров там, где возможно.

Как читать ошибки?

Перед самим списком, давайте быстро взглянем на структуру сообщения об ошибке. Понимание структуры помогает понимать ошибки, и вы получите меньше проблем, если наткнетесь на ошибки, не представленные в этом списке.

Типичная ошибка из Chrome выглядит так:

Uncaught TypeError: undefined is not a function

Структура ошибки следующая:

  1. Uncaught TypeError: эта часть сообщения обычно не особо полезна. Uncaught значит, что ошибка не была перехвачена в catch, а TypeError — это название ошибки.
  2. undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение undefined как функцию.

Другие webkit-браузеры, такие как Safari, выдают ошибки примерно в таком же формате, как и Chrome. Ошибки из Firefox похожи, но не всегда включают в себя первую часть, и последние версии Internet Explorer также выдают более простые ошибки, но в этом случае проще — не всегда значит лучше.

Теперь к самим ошибкам.

Uncaught TypeError: undefined is not a function

Связанные ошибки: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected

Возникает при попытке вызова значения как функции, когда значение функцией не является. Например:

var foo = undefined;
foo();

Эта ошибка обычно возникает, если вы пытаетесь вызвать функцию для объекта, но опечатались в названии.

var x = document.getElementByID('foo');

Несуществующие свойства объекта по-умолчанию имеют значение undefined, что приводит к этой ошибке.

Другие вариации, такие как “number is not a function” возникают при попытке вызвать число, как будто оно является функцией.

Как исправить ошибку: убедитесь в корректности имени функции. Для этой ошибки, номер строки обычно указывает в правильное место.

Uncaught ReferenceError: Invalid left-hand side in assignment

Связанные ошибки: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’

Вызвано попыткой присвоить значение тому, чему невозможно присвоить значение.

Наиболее частый пример этой ошибки — это условие в if:

if(doSomething() = 'somevalue')

В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.

Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову this.

Uncaught TypeError: Converting circular structure to JSON

Связанные ошибки: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported

Всегда вызвано циклической ссылкой в объекте, которая потом передается в JSON.stringify.

var a = { };
var b = { a: a };
a.b = b;
JSON.stringify(a);

Так как a и b в примере выше имеют ссылки друг на друга, результирующий объект не может быть приведен к JSON.

Как исправить ошибку: удалите циклические ссылки, как в примере выше, из всех объектов, которые вы хотите сконвертировать в JSON.

Unexpected token ;

Связанные ошибки: Expected ), missing ) after argument list

Интерпретатор JavaScript что-то ожидал, но не обнаружил там этого. Обычно вызвано пропущенными фигурными, круглыми или квадратными скобками.

Токен в данной ошибке может быть разным — может быть написано “Unexpected token ]”, “Expected {” или что-то еще.

Как исправить ошибку: иногда номер строки не указывает на правильное местоположение, что затрудняет исправление ошибки.

Ошибка с [ ] { } ( ) обычно вызвано несовпадающей парой. Проверьте, все ли ваши скобки имеют закрывающую пару. В этом случае, номер строки обычно указывает на что-то другое, а не на проблемный символ.

Unexpected / связано с регулярными выражениями. Номер строки для данного случая обычно правильный.

Unexpected; обычно вызвано символом; внутри литерала объекта или массива, или списка аргументов вызова функции. Номер строки обычно также будет верным для данного случая.

Uncaught SyntaxError: Unexpected token ILLEGAL

Связанные ошибки: Unterminated String Literal, Invalid Line Terminator

В строковом литерале пропущена закрывающая кавычка.

Как исправить ошибку: убедитесь, что все строки имеют правильные закрывающие кавычки.

Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference

Попытка прочитать null или undefined так, как будто это объект. Например:

var someVal = null;
console.log(someVal.foo);

Как исправить ошибку: обычно вызвано опечатками. Проверьте, все ли переменные, использованные рядом со строкой, указывающей на ошибку, правильно названы.

Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference

Попытка записать null или undefined так, как будто это объект. Например:

var someVal = null;
someVal.foo = 1;

Как исправить ошибку: это тоже обычно вызвано ошибками. Проверьте имена переменных рядом со строкой, указывающей на ошибку.

Uncaught RangeError: Maximum call stack size exceeded

Связанные ошибки: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow

Обычно вызвано неправильно программной логикой, что приводит к бесконечному вызову рекурсивной функции.

Как исправить ошибку: проверьте рекурсивные функции на ошибки, которые могут вынудить их делать рекурсивные вызовы вечно.

Uncaught URIError: URI malformed

Связанные ошибки: URIError: malformed URI sequence

Вызвано некорректным вызовом decodeURIComponent.

Как исправить ошибку: убедитесь, что вызовы decodeURIComponent на строке ошибки получают корректные входные данные.

XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource

Связанные ошибки: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at some/url

Эта проблема всегда связана с использованием XMLHttpRequest.

Как исправить ошибку: убедитесь в корректности запрашиваемого URL и в том, что он удовлетворяет same-origin policy. Хороший способ найти проблемный код — посмотреть на URL в сообщении ошибки и найти его в своём коде.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Связанные ошибки: InvalidStateError, DOMException code 11

Означает то, что код вызвал функцию, которую нельзя было вызывать в текущем состоянии. Обычно связано c XMLHttpRequest при попытке вызвать на нём функции до его готовности.

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Some-Header', 'val');

В данном случае вы получите ошибку потому, что функция setRequestHeader может быть вызвана только после вызова xhr.open.

Как исправить ошибку: посмотрите на код в строке, указывающей на ошибку, и убедитесь, что он вызывается в правильный момент или добавляет нужные вызовы до этого (как с xhr.open).

Заключение

JavaScript содержит в себе одни из самых бесполезных ошибок, которые я когда-либо видел, за исключением печально известной Expected T_PAAMAYIM_NEKUDOTAYIM в PHP. Большая ознакомленность с ошибками привносит больше ясности. Современные браузеры тоже помогают, так как больше не выдают абсолютно бесполезные ошибки, как это было раньше.

Какие самые непонятные ошибки вы встречали? Делитесь своими наблюдениями в комментариях.

P.S. Этот перевод можно улучшить, отправив PR здесь.

Are you stuck to this “typeerror: res.json is not a function” error message while doing your program?

And so, continue reading to fix this error.

In this article, we’ll hand you the solutions for “res.json is not a function.” 

But before that, we’ll give you first a better understanding of this error.

The “typeerror: res.json is not a function” is an error message that can occur when working with Node.js applications and Express.

This error message indicates that the res.json() method, used to send JSON responses to clients, is not recognized as a function by the application.

For example:

const express = require('express');
const app = express();

app.get('/json', (res, req) => {
  res.json({ "message": "Hello json" });
});

app.listen(3000);

As you can see in our example, the arguments in the callback function are in the wrong order.

The first argument should be req (request), and the second should be res (response).

As a result, it will throw a “typeerror: res.json is not a function” error message.

Why does this error occur?

This error can occur for several reasons, such as:

❌ Overwriting the res variable in the code.

❌ Having the arguments in the handler method in the wrong order.

❌ Including version mismatches between dependencies.

❌ Missing middleware configuration

❌ Incorrect function calls

❌ Outdated Node.js versions.

How to fix “typeerror: res.json is not a function”?

Now that you fully understand why this error occurs in your code.
Let’s jump into the solutions to resolve this error.

Solution 1: Check the order of the arguments in the callback function

Ensure that the first argument is req (request) and the second is res (response).

For example:

app.get('/json', (res, req) => {
  res.json({ "message": "Hello json" });
});

To fix this error, you have to switch the order of the arguments.

const express = require('express');
const app = express();

app.get('/json', (req, res) => {
  res.json({ "message": "Hello json" });
});

app.listen(3000);

Solution 2: Avoid overwriting the res variable

Ensure that you are not overwriting the res variable in a callback function.

For example:

app.post('/danger', function response(req, res) {
  let placeId = req.body.data;
  let option = {
    uri: 'https://maps.googleapis.com/maps/api/directions/json?',
    qs: {
      origin: `place_id:${placeId[0]}`,
      destination: `place_id:${placeId[1]}`,
      language: 'en',
      mode: 'running',
      alternatives: true,
      key: APIKey
    }
  };
  rp(option)
    .then(function (response) { //change the variable name of "res" to "response"
      let dangerRate = dangerTest(JSON.parse(response), riskGrid);
      res.json({ data: [response, dangerRate] });
    })
    .catch(function (err) {
      console.error("Failed to get JSON from Google API", err);
    })
});

Solution 3: Ensure that you have included the required dependencies

Ensure that you have included all the required dependencies such as Express

For example:


const express = require('express');
const app = express();

Solution 4: Verify if you are using a library that makes .json a function

Unless you are using a library that makes .json a function, JavaScript uses JSON with two methods .parse() and .stringify().

When you are trying to set an object property by the name of .json.

res.json = { data: [res, dangerRate] };

Solution 5: Verify if you are using the new httpClient library

With the new httpClient library, you don’t have to call the .json() method.
You can use this simple map instead of the json method:

.map(res => res);

Difference between “res.json is not a function” and “responce.json is not a function”?

Both res.json is not a function and responce.json is not a function are error messages that may occur in the context of web development.

If you are confused about either of these two is the same, well the answer is “No.”

Response.json and res.json are not the same.

Response.json res.json
response.json is a method on the Response object in the Fetch API that reads the response and returns a promise that resolves with the result of parsing the body text as JSON. Res.json is a method on the res object in Express.js that sends a JSON response.

Both indicate that the json method is not recognized as a function of the response or res object, respectively.

The difference between the two error messages is the name of the variable used to reference the response object.

Conclusion

The “typeerror: res.json is not a function” is an error message that can occur when working with Node.js applications and Express.

This article already provides several solutions above so that you can fix the error message immediately.

We are hoping that this article provided you with sufficient solutions to get rid of the error.

You could also check out other “typeerror” articles that may help you in the future if you encounter them.

  • Typeerror: unhashable type: ‘dataframe’
  • Typeerror: ‘classmethod’ object is not callable
  • Typeerror: failed to construct ‘url’: invalid url

The freeCodeCamp Forum

Loading

Понравилась статья? Поделить с друзьями:
  • Is mf02 5 ошибка gta v
  • Is mf01 ошибка доступа к файлу установки
  • Is lulu is in the garden где ошибка
  • Is fc05 файл поврежден код ошибки
  • Is done dll произошла ошибка при распаковке