1

I am building out a webpage which needs to make a call to the Google Geocoder api. In order to hide the api key from public view, I am trying to set up server middleware to act as a REST api endpoint.

I have checked through all of the documentation and copied all of it, but the response is always the same. I receive the entirety of the html body back from the axios request rather than anything else I send back via express.

In my component I have the following code:

  computed: {
    normalizedAddress() {
      return `${this.member.address.street} ${this.member.address.city}, ${this.member.address.state} ${this.member.address.zip}`.replace(
        /\s/g,
        '+'
      )
    }
  },
  methods: {
    async getLocation() {
      try {
        const res = await axios.get(
          `/api/geocode/${this.normalizedAddress}`
        )
        console.log(res)
      } catch (err) {
        console.log(err)
      }
    }
  },

In nuxt.config.js I have this setup

serverMiddleware: ['~/api/geocode.js'],

In the root of my project I have an api folder with geocode.js stored there. geocode.js is below

import express from 'express';
import axios from "axios";
let GEO_API = "MY_API_KEY"

const app = express();
app.use(express.json());

app.get("/", async (req, res) => {
   const uri = `https://maps.googleapis.com/maps/api/geocode/json?address=${req.params.address}&key=${GEO_API}`
   try {
      const code = await axios.get(uri);
      if (code.status !== "OK") {
         return res.status(500).send(code.status)
      }
      return res.status(200).send(code);
   } catch (err) {
      return res.status(500).send(err);
   }
});

export default {
   path: "/api/geocode/:address",
   handler: app
}

Again. The response always has the entire html document from the website sent back (some 100 pages of code). Even when I set the response to fixed text, that is not sent.

The only detail I can think of that might be interrupting it is that I have my own custom routing setup using the @nuxtjs/router build module in use.

kissu
  • 40,416
  • 14
  • 65
  • 133
  • Does it do the same via postman? – kissu Jul 12 '21 at 22:18
  • postman does not encounter the same issue, but it also bypasses the express middleware altogether. It is definitely not reaching the middleware because I attempted just to send back "test" previously and that did not come through at all. – Brad Chandler Jul 14 '21 at 00:00

0 Answers0