I'm trying to deploy my app to Heroku in which I believe is working. Whilst testing my app via localhost it works fine, everything is posting. However after deployment and replacing all my URLs to Heroku, number of things are not working:
The GIPHY API no longer works
Nothing would post (comments and likes work but not the posting)
I have tried debugging however nothing has worked. Where am I going wrong? Please see below for details
app: https://mitnickproject1-journal-app.netlify.app/
heroku: https://journal-post-pl.herokuapp.com/print
Front-end code
const formEl = document.querySelector('form');
formEl.addEventListener('submit', postFormData)
let count=0;
async function postFormData(e) {
const current= new Date().toLocaleString()
const formData= new FormData(formEl) // console.log this to check what format this is in
const formDataSerialised=Object.fromEntries(formData) //console.log this to see what this does
const jsonObject = {...formDataSerialised, "dateTime": current, "comment": [], "EmojiCount": [0,0,0], "gifLink":gifLink, 'id': count}
console.log(JSON.stringify(jsonObject, null, 2))
try{
const options = { method: 'POST',
body: JSON.stringify(jsonObject),
headers: {
'Content-Type': 'application/json'
}
}
await fetch("https://journal-post-pl.herokuapp.com/test", options);
// const response = await fetch("https://journal-post-pl.herokuapp.com/test", {
// })
// const json = await response.json();
}catch(err){
console.error(err);
alert('There was an error')
}
}
Back End Code
app.post('/test', (req, res) => {
formData.push(req.body)
console.log(formData)
writeToJson();
res.json({success: true})
})
Any help would be appreciated
I checked out your code and tested it out while looking at the console.
Your GIPHY urls are using http instead of https. http is fine for development, but live site needs to use https. Just switch all your http urls to https and that will work.
Your server isn't set up to accept any requests from an outside source (AKA CORS). To fix this, just add app.use(cors()) to your server file.
Don't forget to put const cors = require('cors') at the top.
Related
I have the latest 59.0.0 ipfs-http-client and I have tried with multiple versions but the same problem arises. I have set up infura project, I have the Project Id, API key... also I have set up authentication headers but when i go and add the file... it takes a bit of time and then returns a Uri hash with 400 bad request marked red in. I am attaching the console log and codes.
I am using Next Js, this is the connection bit of code.
import { create as ipfsClient } from 'ipfs-http-client';
const auth =
'Basic ' + Buffer.from(PROJECT_ID + ':' + API_KEY_SECRET).toString('base64');
const client = ipfsClient({
host: 'ipfs.infura.io',
port: 5001,
protocol: 'https',
headers: {
authorization: auth,
},
});
This the bit where try and pin the file.
const file = e.target.files[0];
try{
const added = await client.add(
file,
{
progress: (prog) => console.log(`received: ${prog}`)
}
)
const url = `https://ipfs.infura.io/ipfs/${added.path}`;
setFileUrl(url);
}
catch(error){
console.log(error);
}
I have tried using mutiple versions of ipfs-http-client, I even tried with old versions where I would just have to give a global uri without any authentication
ipfs-http-client#50.1.2
const client = ipfsHttpClient('https://ipfs.infura.io:5001/api/v0');
but nothing seems to be working and please forgive me I am a novice to this.
So i have a vue project where i have a js file that requests data from an API and that goes fine. I set up a proxy in my vue.config.js file so that every request starting with /api will be redirected to the baseurl of the API, like this:
const { defineConfig } = require('#vue/cli-service');
const path = require('path');
module.exports = defineConfig({
transpileDependencies: true
})
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://dev.liveflow.nl'
},
}
}
}
This works fine for when im in my websites base url and do an axios.get request like axios.get(api/batches/). But when im in my websites 'batches' route, and i do axios.get(api/batches/:id/, the proxy doesnt work. Instead of requesting to (target from the vue.config.js file above) target/api/batches/:id, its requesting to my own websites url/batches/api/batches/:id. So the problem is, that because im in the /batches route, it will leave the /batches in the url, so the proxy i configured doesnt work (i think)
So the code i use in my js file to do all http requests looks like this:
import axios from "axios";
const url = "api/batches/";
class BatchService {
// Get Batches
static async getBatches() {
try {
const res = await axios.get(url);
const data = res.data;
return data;
} catch(err) {
return err;
}
}
// Get Batch by ID
static async getBatchById(id) {
try {
const res = await axios.get(`${url}${id}`);
const data = res.data;
return data;
} catch(err) {
return err;
}
}
export default BatchService;
Because of the proxy, i only have to do "api/batches/" as url, because the proxy recognizes the /api and redirects it to the target.
These to methods work fine when im in my websites baseurl, but when im in a different route, like baseurl/batches, the requests does baseurl/batches/api/batches/:id, while i want it to be target/api/batches/:id.
The error i get is simple: GET http://localhost:8080/batches/api/batches/63722a8ab1194203d268b220 404 (Not Found). It is just requesting the wrong url and using the websites baseurl instead of the target baseurl.
BTW: I need to do the proxy setup. When i just do const url = "target/api/batches/" the API server will deny my request
My english is not that good so i hope im clear enough.
I have a Nuxt.js app that I'm trying to deploy to Netlify - and everything works on my local machine, but the fetch request to the api returns a 404 when it's deployed to Netlify. I don't know how to make that server route available to my client when it's deployed.
the fetch request in my api-client.js file looks like this:
async fetchInfo(state) {
let response = await fetch(`/api/info/${state}`);
let data = await response.json();
return data;
}
and the api looks like this (in api/index.js file):
const rp = require('request-promise');
const apiKey = process.env.POLICY_API_KEY;
export default function (req, res, next) {
if (req.url.includes("/info")) {
let stateAbbr = req.originalUrl.slice(-2);
rp({
uri: `https://third-party-api-here.com/states/${stateAbbr}/`,
method: 'GET',
headers: {
'token': apiKey,
},
json: true
}).then(function success(response) {
if (response) {
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(response));
return;
}
}).catch(function error(response) {
console.log('error', response.error);
});
return;
}
next();
}
I think this might have something to do with CORS? I'm getting this error in the browser when I try to hit that route in the deployed app:
GET https://my-app-name.netlify.app/api/info/MN 404
SyntaxError: Unexpected token < in JSON at position 0
As mentioned in the comment above, you need to have a Node.js of some sort.
Hence, hosting on Heroku fixed OP's issue (Netlify is only for static files).
I am using Node Js as backend and basic html css js for frontend. I am sending request through node js that
app.get("/send", async (req, res) => {
let products = await Product.find();
products = await products;
res.send(products);
});
and getting fetch on an html page:
const getData = async () => {
const response = await fetch("localhost:3000/send", {
method: "GET",
});
const data = await response.json();
console.log(data);
};
getData();
But i am not getting the data, I have tested the api on Postman it works fine there. But throwing error on browser:
Error is :
Fetch API cannot load localhost:3000/send. URL scheme "localhost" is not supported.
Please help me out. Bundles of thanks!
You should specify localhost as being http://localhost or https://localhost - otherwise fetch can't be sure which protocol you are mentioning:
const response = await fetch("http://localhost:3000/send", { ... });
I'm running a server with nodejs+mongodb:
let MongoClient = require('mongodb').MongoClient.connect("mongodb://localhost:27017/mydb", { useNewUrlParser: true } ),
(async () =>{
let client;
try {
client = await MongoClient;
...
I'm creating some data-visualizations and I need a simple way to access my backend data from javascript, is this possible? Ideally I would like full access.
You have to build a bridge, e.g. using a REST API:
// server.js
// npm install express, body-parser, mongodb
const app = require("express")();
const bodyParser = require("body-parser");
const db = require("mongodb").MongoClient.connect(/*...*/);
app.use(bodyParser.json());
app.post("/findOne", async (req, res) => {
try {
const connection = await db;
const result = await connection.findOne(req.body);
if(!result) throw new Error("Not found!");
res.status(200).json(result);
} catch(error) {
res.status(500).json(error);
}
});
// ... all those other methods ...
app.listen(80);
That way you can easily connect to it on the client:
// client.js
function findOne(query) {
const result = await fetch("/findOne/", {
method: "POST",
body: JSON.stringify(query),
headers:{
'Content-Type': 'application/json'
}
});
if(!result.ok) throw await result.json();
return await result.json();
}
Note: I hope you are aware that you also allow some strangers to play with your database if you do not validate the requests properly / add authentication.
For security purposes you should never do this, but hypothetically you could make an AJAX endpoint or WebSockets server on the node application that passes the input straight to mongoDB and takes the output straight back to the client.
It would be a much better practice to write a simple API using AJAX requests or WS to prevent the user from compromising your database.