17

I'm trying to send two json but It doesn't work. It prints TypeError: res.json is not a function but I don't get why It happens. Is there any ideas? Thank you !!

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: 'walking', alternatives: true, key: APIKey
      }
    };
    rp(option)
      .then(function(res) {
        let dangerRate = dangerTest(JSON.parse(res), riskGrid);
        res.json({ data: [res, dangerRate]});
      })
      .catch(function(err) {
        console.error("Failed to get JSON from Google API", err);
      })
});
1
  • 1
    @BelminBedak Why would that matter? Commented Feb 6, 2017 at 19:30

8 Answers 8

30

Because you're overwriting your res variable in the .then of your rp function:

app.post('/danger', function response(req, res) { //see, "res" here was being overwritten
   ..
   ..
   rp(option).then(function(response) { //change the variable name of "res" to "response" (or "turtles", who cares, just dont overwrite your up most "res")
Sign up to request clarification or add additional context in comments.

Comments

19

I got this error message because I had the arguments in the wrong order in the handler method. (amateur's fault)

Wrong order: (res, req)

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

Right order: (req, res)

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

1 Comment

Works for me in typescript: typescript app.get('/', (req: Request, res: Response, next: NextFunction) => { res.json({ message: 'Welcome to my API' }); }); Also, error comes first.
4

.json isn't a function. Unless you are using a library that makes it one, JavaScript uses JSON (with two methods .parse() and .stringify() one of which you use in the line above).

If you are trying to set an object property by the name of .json then it would be:

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

1 Comment

As most people use express its worth pointing out this: expressjs.com/en/api.html#express.json
1

With new httpClient libary, you don't need to call .json() method, Just use this simple map instead of the json method.

.map(res => res );

Comments

0

check the sequence=>

If you have write nested res and you write (res,req) you get error.

Comments

0

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");
});

Comments

0

This error occured for me because of me using express.Router() instead of express() while initializing the app I wrote the below line const express = require("express"); const app = express().Router;

Correct way is to write this const express = require("express"); const app = express();

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
0

This is a general solution to the TypeError: res.json is not a function error, arguments should be in the order (req, res)

On Typescript:

import { Request, Response } from 'express';
const router = require('express').Router();
  
router.get('/', (req: Request, res: Response) => {
      return res.json({ name: 'My Name' });
});

module.exports = router;

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.