Express API returning HTML, not JSON, on GET request w/ JWT Token

I’ve been trying to wrap my head around this all day. I’m trying to figure out where this token is…. Any ideas?

All I keep getting is the following error and a return in text/html from my Express backend

SyntaxError: Unexpected token   in JSON at position 3

index.js

const express = require("express");
const app = express();
const cors = require("cors");
var bodyParser = require("body-parser");
const dotenv = require('dotenv');
const { default: mongoose } = require("mongoose");

const auth_routes = require('./routes/auth.routes');
const rate_routes = require('./routes/rate.routes');

dotenv.config();

const port = process.env.PORT || 5000;
const mongo_uri = 'mongodb://' + process.env.MONGO_USER + ':' + process.env.MONGO_PASSWD + '@localhost:27017/home?authSource=admin';

mongoose.connect(mongo_uri)
.then((resp) => {
    console.log('Connected to MongoDB');
}).catch((err) => {
    console.error('Error: ', err.reason)
});

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

app.listen(port, () => { console.log("Server is running on port 5000");});

...
...

app.get('/', (req, res) => {
    res.send("Welcome to the Behemoth API platform")
});

app.set('userToken', userToken);
app.use('/v1/user', auth_routes);
app.use('/v1/rates', rate_routes);

rate.routes.js – the api call

const express = require('express');
const auth_middle = require('../middleware/auth');
const axios = require("axios");
const router = express.Router();

router.route('/').get(auth_middle, async function (req, res) {
    try {
        let userToken = req.app.get('userToken');
        const reqBody = [ {
              ....
              ....
        } ];

        let rateResponse = await axios.post('https://xxxxxxxx', reqBody, {
            headers: {
                'Authorization': 'Bearer ' + userToken
            }
        });

        var StockRate = rateResponse.data.StockData;

        res.send(rateResponse.data);

    } catch (e) {
        console.log(e.stack);
        res.status(500).send({error: e.message + " / " + e.keyword });
    }

});

module.exports = router;

auth.js

const jwt = require('jsonwebtoken');
const dotenv = require('dotenv');

dotenv.config();

module.exports = (req, res, next) => {
    try {
        console.log(req.headers.authorization);
        const token = req.headers.authorization.split(" ")[1];

        jwt.verify(token, process.env.JWT_SECRET_KEY);
        next();
    } catch (err) {
        console.log(err);
        res.send(401).json({ message: err })
    }
}

Google places API getDetails() service not returning ratings for any location

I’ve been trying to build a bicycle assistant and I’m trying to show the phone number and rating for the destination the user enters.

I have some code that gets me the entire request in the form below (copied from firefox console)


address_components: Array(6) [ {…}, {…}, {…}, … ]
​
adr_address: "<span class="street-address">Times Sq</span>, <span class="locality">New York</span>, <span class="region">NY</span>, <span class="country-name">USA</span>"
​
formatted_address: "Times Sq, New York, NY, USA"
​
geometry: Object { location: {…}, viewport: {…} }
​
html_attributions: Array []
​
icon: "https://maps.gstatic.com/mapfiles/place_api/icons/v1/png_71/geocode-71.png"
​
icon_background_color: "#7B9EB0"
​
icon_mask_base_uri: "https://maps.gstatic.com/mapfiles/place_api/icons/v2/generic_pinlet"
​
name: "Times Square"
​
place_id: "ChIJO8I76FVYwokR2nYv8Wdvie0"
​
reference: "ChIJO8I76FVYwokR2nYv8Wdvie0"
​
types: Array [ "route" ]
​
url: "https://maps.google.com/?q=Times+Sq,+New+York,+NY,+USA&ftid=0x89c25855e83bc23b:0xed896f67f12f76da"
​
utc_offset: 
​
utc_offset_minutes: -240
​
vicinity: "Manhattan"

I get legitimate details for all the place IDs I search for, such as phone number and address. However, I do not get the rating for any of them.

I tried popular places too but no ratings field. I haven’t added any field filters either. Below is my setup for the request for reference.


function fetchmoredeets(addr) {
    var loc = addr.split(' ').join('+')
    const URL = `https://cors-anywhere.herokuapp.com/https://maps.googleapis.com/maps/api/place/textsearch/json?query=${loc}&key=(my_key)`
    // First get and parse the nearby regions

    async function fetcher(URL){
        const resp = await fetch(URL);
        return await resp.json()
    }

    var res, req;
    (async () => {
      req = await fetcher(URL);
      res = req.results;
      console.log("All deets helper:", res[0]);
      var deetsreq = {
              placeId: res[0].place_id,
            };

            var service = new google.maps.places.PlacesService(map);
            service.getDetails(deetsreq, callback);

            function callback(place, status) {
              if (status == google.maps.places.PlacesServiceStatus.OK) {
                console.log(place);
                document.getElementById("table-title").innerHTML = res[0].name
                var table = document.getElementById("deets-entries");
                var r = table.insertRow();
                r.insertCell().innerHTML =  place.address_components[1].short_name + ' ' + place.address_components[2].short_name; // addr

                r.insertCell().innerHTML= place.ratings; // rating
                if(place.formatted_phone_number==null){
                    r.insertCell().innerHTML= "NA";
                }
                else{
                    r.insertCell().innerHTML= place.formatted_phone_number;
                }
              }
            }


})()
}

Above, addr is a string with the address of the place (based on the user’s selection from google’s places autocomplete API)

Any help would be great! Thanks

Vuejs stuck on 51% when building

I’ve read all the other stack overflow questions regarding this; I’ve checked after template there is some sort of main wrapper like a div or v-container (I’m using vuetify). I’ve tested my page by just having the template tag a container and a heading with some text. My branch is up to date with main branch, I’ve run serve multiple times, I’ve restarted the pc and vscode, and deleted node modules.

I also stopped node.js process in task manager

All of a sudden building always stuck on 51%

My code:

<template>
  <v-container fluid>
    <h1>hello world</h1>
  </v-container>
</template>

<script>
export default {

}
</script>

<style>
/*  */
</style>

Sending image buffer as response and saving it on client side

Before anyone marks this question as DUPLICATE, the image buffer is not created by me, it’s an API response and I want to send that buffered image to the client to save it. I have tried all available solutions on StackOverflow and my code looks like this right now. For info about the response type from API, please check here

Server:

sharp(buff).toFormat('png').toBuffer()
        .then(data =>{
            
           const bufferedimage = data
           console.log(bufferedimage.buffer)

            res.send(bufferedimage);
    
        } )
        .catch(err=>{ console.log(err)})

Client:

 fetch(`http://127.0.0.1:8000/webptojpg?image=${url}`).
then(res=>res.json())
.then(results=>{
    console.log(results)
    const blob = new Blob([results])
    // base64Img=new Blob(results.image.data,{type:'Buffer'});
    img = document.createElement('a')
    img.href = window.URL.createObjectURL(blob)
    img.download = "result.png";
    img.click()
    
})
.catch(err=>console.log(err))

NPM: “Can’t resolve ‘process/browser.js'” error

NPM v7.5.2 running on Raspbian

$npm install was run without error, it was only when I ran $ sudo npm run prod in /var/www/projectdir (projectdir is the directory for the web framework I’m using). When I ran that command, I received the below output and error message:

> prod

> npm run production

> production

> mix --production

✖ Mix

Compiled with some errors in 2.56m

● Mix █████████████████████████ done (99%)

plugins

ERROR in ./node_modules/axios/lib/defaults.js 22:20-27

Module not found: Error: Can't resolve 'process/browser.js' in '/var/www/projectdir/node_modules/axios/lib'

webpack compiled with 1 error

npm ERR! code 1

npm ERR! path /var/www/projectdir

npm ERR! command failed

npm ERR! command sh -c mix --production

npm ERR! A complete log of this run can be found in:

npm ERR! /root/.npm/_logs/2022-07-13T21_45_17_200Z-debug.log

npm ERR! code 1

npm ERR! path /var/www/projectdir

npm ERR! command failed

npm ERR! command sh -c npm run production

npm ERR! A complete log of this run can be found in:

npm ERR! /root/.npm/_logs/2022-07-13T21_45_17_714Z-debug.log

Here are the Logs from /root/.npm/_logs/2022-07-13T21_45_17_714Z-debug.log:

https://pastebin.com/1mFw8ufg

Any suggestions appreciated

Why is fetch calling api multiple times in react?

I have a very basic api and all it does is return the text “Sunny day”.

I create a react project using create react app and try to call the api once then printing result to the console.

Here is the react app

import logo from './logo.svg';
import './App.css';

function App() {

  fetch('https://localhost:44386/weatherforecast')
  .then(response => response.text())
  .then(data => console.log(data));

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

The problem is the api is getting called twice on page load

Can anybody explain why?

Cannot add response headers

This is the script I’m using:

const securityHeaders = [
  {
    key: 'X-XSS-Protection',
    value: '1; mode=block'
  },
  {
    key: 'Referrer-Policy',
    value: 'origin-when-cross-origin'
  }
]

module.exports = {
  async headers() {
    return [
      {
        // Apply these headers to all routes in your application.
        source: '/:path*{/}?',
        headers: securityHeaders,
      },
    ]
  },
}

But when I run npm run start and check the Response Headers for localhost, none of these headers appears.

Using next version 9.5.2

Use React Homepage instead of default Firebase Hosting index.html

When I initiate firebase hosting in my react app, it automatically generates an index.html file which it uses as the “home screen” or the initial screen that you get when you open the site. How can I change this to use my “Home.js” file instead?

From the initiation, these were my answers to the questions

? What do you want to use as your public directory? src
? Configure as a single-page app (rewrite all urls to /index.html)? No
? Set up automatic builds and deploys with GitHub? No

Make a plane appear only on capture

Just started working in Spark AR and it seems pretty easy to make an object not visible when capturing, whether that is using the CameraInfo class or ObjectVisibility class. I’ve gotten that to work. However, what I can’t get to work is the opposite. Basically, I have a plane with a texture attached that I would like to be hidden while the filter runs, but then when capturing a photo the plane becomes visible.

I thought I could just reverse the logic of how it worked above, basically with something like “if camera is capturing photo, then plane.hidden = false.) Or something like that, written in non-pseudocode of course. But that doesn’t work. My guess is that there isn’t enough time elapsing between the capture instruction to allow the plane visibility to be enabled, but could be wrong. Anyone have any ideas?

How to get element in React without document querySelector?

Now I insert some HTML to my react project with ‘dangerouslySetInnerHTML’, like this.

...

return (
  <>
    <section className="PersonalReading__pages__rightPage">
            <div style={{margin: 'auto', position: 'relative', width: '100%', height: '130%', overflow: 'hidden'}} dangerouslySetInnerHTML={{ __html: htmlWantToShow}}></div>
    </section>

...

In this situation, I want to manuplate some Dom element in that html rendered by dangerouslySetInnerHTML={{ __html: htmlWantToShow}}.
And now Im using document.querySelector to do that.

example, in my code, document.querySelector('.whatIWantToManipulateDom').style.backgroundColor = 'yellow'; exists, and whatIWantToManipulateDom is in that htmlWantToShow rendered by dangerouslySetInnerHTML={{ __html: htmlWantToShow}}.

Actually, I know I should use useRef.

But I am not familiar with React, and I don’t know how to transplant ref attribute into that htmlWantToShow’s element to use useRef.

Because using document.querySelector makes debugging difficult, and also now many errors occur in my project when i use axios to send and receive data. now im failing to send and receive data intermittently

I want to use useRef instead of document.querySelector for using React correctly.

Im sorry for that im not goot at English, But please help me. Thanks for reading my question.

How to integrate AWS IVS with JW Player?

I’m trying to follow this IVS sample, the only difference is using the JW player, I following this documentation

The problem is that this snippet

  jwplayer(videoPlayer).addEventListener(
    PlayerEventType.TEXT_METADATA_CUE,
    function (cue) {
      const metadataText = cue.text;
      const position = player.getPosition().toFixed(2);
      console.log(
        `Player Event - TEXT_METADATA_CUE: "${metadataText}". Observed ${position}s after playback started.`
      );
      triggerQuiz(metadataText);
    }
  );

is giving this error

script.js:60 Uncaught TypeError: Cannot read properties of undefined (reading 'TEXT_METADATA_CUE')

I’m either not adding an event listener to the jw player correctly or I’m doing something wrong while working with IVS.

My full code is below

const playbackUrl =
  "https://fcc3ddae59ed.us-west-2.playback.live-video.net/api/video/v1/us-west-2.893648527354.channel.xhP3ExfcX8ON.m3u8";

const videoPlayer = document.getElementById("video-player");
const quizEl = document.getElementById("quiz");
const waitMessage = document.getElementById("waiting");
const questionEl = document.getElementById("question");
const answersEl = document.getElementById("answers");
const cardInnerEl = document.getElementById("card-inner");
var ivsPlayer = {};
var ivsEvents = {};
const ivsConfig = {
  playlist: [
    {
      file: playbackUrl,
      type: "ivs",
    },
  ],
};

(function (ivsPlayer) {
  jwplayer(videoPlayer)
    .setup(ivsConfig)
    .on("providerPlayer", function (player) {
      console.log("Amazon IVS Player: ", player.ivsPlayer);
      console.log("Amazon IVS Player Events: ", player.ivsEvents);

      // store the reference to the Amazon IVS Player
      ivsPlayer = player.ivsPlayer;
      // store the reference to the Amazon IVS Player Events
      ivsEvents = player.ivsEvents;
    });
  const PlayerState = ivsPlayer.PlayerState;
  const PlayerEventType = ivsPlayer.PlayerEventType;
 

  jwplayer(videoPlayer).addEventListener(
    PlayerEventType.TEXT_METADATA_CUE,
    function (cue) {
      const metadataText = cue.text;
      const position = player.getPosition().toFixed(2);
      console.log(
        `Player Event - TEXT_METADATA_CUE: "${metadataText}". Observed ${position}s after playback started.`
      );
      triggerQuiz(metadataText);
    }
  );

  // Setup stream and play

  // Remove card
  function removeCard() {
    quizEl.classList.toggle("drop");
  }

  // Trigger quiz
  function triggerQuiz(metadataText) {
    let obj = JSON.parse(metadataText);

    quizEl.style.display = "";
    quizEl.classList.remove("drop");
    waitMessage.style.display = "none";
    cardInnerEl.style.display = "none";
    cardInnerEl.style.pointerEvents = "auto";

    while (answersEl.firstChild) answersEl.removeChild(answersEl.firstChild);
    questionEl.textContent = obj.question;

    let createAnswers = function (obj, i) {
      let q = document.createElement("a");
      let qText = document.createTextNode(obj.answers[i]);
      answersEl.appendChild(q);
      q.classList.add("answer");
      q.appendChild(qText);

      q.addEventListener("click", (event) => {
        cardInnerEl.style.pointerEvents = "none";
        if (q.textContent === obj.answers[obj.correctIndex]) {
          q.classList.toggle("correct");
        } else {
          q.classList.toggle("wrong");
        }
        setTimeout(function () {
          removeCard();
          waitMessage.style.display = "";
        }, 1050);
        return false;
      });
    };

    for (var i = 0; i < obj.answers.length; i++) {
      createAnswers(obj, i);
    }
    cardInnerEl.style.display = "";
  }

  waitMessage.style.display = "";
})(window.ivsPlayer);

Set animation direction via Javascript/Typescript

Through Typescript I have to set an animation in a component defined in the html template.

To do this I am using the “animate (keyframes, options)” method.

In the options I would like to set the “alternate” direction but I don’t know how to do it because the property is of type Playbackdirection which is an interface. How can I do it?

Here my code:

animate() {

const progress = document.querySelector(".progress") as HTMLElement;

if (progress !== null){
  const options = {
    duration: 2000,
    easing: "ease-in-out",
    iterations: 2,
    direction: "alternate" //ERROR HERE
  }

  progress.animate({
    width: ["0%", "10%", "20%", "30%", "40%", "50%", "60%", "70%", "80%", "80%", "80%"],
    backgroundSize: ["0%", "1000%", "500%", "333%", "250%", "200%", "166%", "142%", "125%", "125%", "125%"]
  }, options);
}

}

strange behaviour of promise looping indefinitely

Having this script:

const got = require("got");
const getStream = require("get-stream");
const app = require("express")();

async function httpGet() {
  console.log("getting response");
  let targetUrl = "http://localhost:3000/api";
  let gotOptions = {
    method: "get",
    headers: { "content-type": "application/json" },
    body: undefined,
    retries: 0
  };
  let response = await new Promise(async (resolve, reject) => {
    let stream = got.stream(targetUrl, gotOptions);
    stream.on("error", async error => {
      try {
        resolve(stream);
      } catch (err) {
        reject(err);
      }
    });
    stream.on("response", async res => {
      try {
        resolve(await getStream(res));
      } catch (err) {
        reject(err);
      }
    })
  });
  return response;
}

async function apiMiddleware(req, res, next) {
  try {
    const response = await httpGet();
    console.log(response);
  } catch (e) {
    throw new Error("some error");
  }
  next();
}

app.use("/", [apiMiddleware]);

app.get("/api", (req, res) => {
  res.json({ data: "some output" });
});
app.get("/someapp", (req, res) => {
  res.end();
});

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

Will (upon visiting “localhost:3000/someapp”) console.log

getting response
getting response
getting response
getting response
getting response
getting response
getting response
getting response
getting response
getting response
getting response
...

When debugging, the promise will always throw me at the start of httpGet(), so what is going on?