Error Unable to find JSON file in folder, Javascript - javascript

Trying to fetch my json file, but apparently the URL is invalid or wrong as per the warning.
Tried to console log modelURL and it looks correct. Console.log Output : ./tm-my-image-model/model.json
Full error
Uncaught Error: Request to ./tm-my-image-model/model.json failed
with status code 404
const URL = ./tm-my-image-model/;
let model, webcam, maxPredictions, happy, sad, angry;
let refresh = true;
async function init() {
if (refresh) {
refresh = false;
const metadataURL = URL + "metadata.json";
const modelURL = URL + "model.json";
console.log(modelURL)
}}
File Structure

How are you doing the fetch? (It is not in the code you provided).
In Node.js to work with the file system you need to use the native module fs.
Node.js v18.2.0 documentation File system

This depends where you're calling it from. Currently, the path is relative, and where it's relative to can get quite confusing quite quickly. Note that if you're able to send the path with the page render, that might be good too, since you can then resolve the path from node, and avoid any ajax.
That being said, if possible (since this looks to be node anyway), it would probably be a whole lot easier to use require("x") (or import x from "x" if ESM), or, if you need it to load asynchronously, using the await import("x") syntax.
If you're using server side rendering only, it may be useful to make a network call and fetch the file from your server asynchronously as well.

Related

How do I get my Python file to print in the terminal instead of in the server it sets up?

I am running a bit of a complicated setup where several files interact with each other:
a python file, setting up a server, which is used to connect two users online
a combination of js and html files to set up the web page that each user interacts with
So each user interacts with the js files, which in turn send a message to the python file, which reacts by sending the appropriate response to the js files on the other user’s end, etc.
To launch all this, I simply open the python file in my terminal — thus opening up the websockets — and then I type in the address of my html file on my browser. I know the functions in my python file are executing correctly because the interaction does work on my browser, however, none of the prints in the functions show up on my terminal…
So for example, in the python file:
def message_received(client, server, message):
print("Client(%d) said: %s" % (client['id'], message))
response = json.loads(message)
response_code = response['response_type']
handle_client_response(client['id'], response_code, response)# another function defined elsewhere
PORT = 9004
print('starting up')
server = WebsocketServer(PORT, '0.0.0.0')# this is calling the actual server set up from another file, which I didn 't write myself.
server.set_fn_message_received(message_received)
server.run_forever()
The "starting up" is the only thing that will actually print, the print in message_received doesn't show up, even though I know for a fact the function is working because handle_client_response is called correctly.
My guess is this is because the function are not actually executed on the terminal, but on the server that I set up, so python is trying to print in the server instead of the terminal. But also I have no idea what I’m talking about — first time I ever do this type of complicated files interaction so I’m very confused!
Am I guessing the problem correctly? Any fix for it?
Try maybe using a library like logging to handle the print of messages. That way, you can specify where the log messages should be written to.
import logging
logging.basicConfig(level=logging.DEBUG)
def message_received(client, server, message):
logging.debug("Client(%d) said: %s" % (client['id'], message))
response = json.loads(message)
response_code = response['response_type']
handle_client_response(client['id'], response_code, response)
Hopefully this will fix it.

Having a hard time getting Api from localhost?

I am on this project wherein I need the api from this specific software. I cannot fetch it when I am trying to fetch it, sometimes error 404 are occuring,
sometimes no-cors policy.
Then sometimes like this: GET http://localhost:8000/events/1003/results net::ERR_CONNECTION_REFUSED
getEvents # orbiter.js:22
(anonymous) # orbiter.js:28
Then sometimes Uncaught (in promise) TypeError:
There are no authorization that needed based on the documentation or headers. Or i thought so it does not have?
But i think this is because of the way that I am fetching the API, it looks like I am doing it wrong. The API as i am trying to get on the instruction on the documentation it says i can access it on "localhost"
At first i just need to open the software to have access on the localhost so the http port will open, then i go to "localhost" then everything is on that local host
This are the picture Screenshot of The LocalHost I need to access
Now based on this I need to get the result of the event. Based on the documentation I need to go to path "localhost/events/{event-id}/results" then a json format would be send back to me.
I go to the url using browser using that path and I get the result, This are the result based on that path but this are the thing, when I am trying to put it on the code using Javascript language es6 module wherein I am fetching the api and I put the link "localhost/events/{event-id}/results"
this are the code:
const link = "http://localhost/events/1003/results";
async function getEvents() {
const response = await fetch(link);
const data = await response.json();
console.log(data);
return data;
}
getEvents();
I cannot access now the data that I needed from the API. Even though the path on the link that I put was correct. Am i missing some steps here? That's all. As you can see, localhost is the main path, then i just follow the path based on the documentation to get the results. (Because what i need to access are the results of the events). Then errors has occurred. This are the documentation that may help you to help me. I hope some of you may help me on this one as I'm still a beginner on programming
https://drive.google.com/drive/u/0/folders/1Il6GPL-pqxeS8OWVOEt36OF-a_FfQwpj

Avoiding Net.createConnection errors in Node

I am currently building an app with React and Node.js
In this app, I need to query a database on my own server with the following function, located in a separate file called "database.js"
const fetchQuery = util.promisify(con.query).bind(con)
// Get all the tracks for a given date from the
const fetchTracks = async (date) => {
const rows = await fetchQuery("SELECT * FROM tracks WHERE playlistDate = '"+date+"'");
}
This works perfectly when I run the file with Node from the command line. However, when I attempt to import it into my react app with
import { fetchTracks, addTracks } from '../scripts/database'
I begin to get errors in the database file, specifically Unhandled Rejection (TypeError): Net.createConnection is not a function on my fetchQuery call.
From what I've read, this happens when attempting to call the function from the browser, as that would pose a security risk. However, as I understand it, all node operations are performed on the server side, right? Why would I be getting this flag when the database is supposedly queried before the page is served? What do I need to do amend this?
React runs in the browser, so as soon as you include database.js in your React app, it's running in the browser with the rest of React, so of course you'll get the error. Making this work gives two options:
expose an API endpoint from Node for React to call, and that API endpoint calls database.js, or,
investigate server-side rendering for React, where some of your React app -- particular the more static parts of it like your main menu -- are created on the Node side and only the final HTML is sent to the browser. (This is a large topic all by itself though.)
By your example which takes a date parameter for the SQL, I'm guessing #2 isn't an option.

React ES6 App - Local API calls

I can't for the life of me figure this out, it seems like it should be straight forward but it's just not clicking.
I have an ES6 app that I created using create-react-app. I've got all the templates and layouts set up for the project and came to trying to pull in data from an API that I want to sit inside the app - like a botched MVC where React handles the views and I run the models and controllers in PHP.
So I have a function in one of my components that I want to fetch some data. I use the fetch() function (I know this isn't yet compatible with a number of browsers but that's a problem for another day) to fetch a relative path from the component to the model I want to load, however the fetch function treats my path as a call to the base URL followed by the request. So with the site running on localhost:3000, I run the following code in my getData() function...
let test = fetch('../models/overall-stats.php').then(function(response) {
console.log(response);
return response;
});
...the URL that fetch hits is then http://localhost:3000/models/overall-stats.php which simply resolves back to the index.html file and loads the app, rather than the PHP file I'm requesting.
If I need to hit that PHP file to get my data, am I wrong in using fetch? Or am I just using it incorrectly? If I shouldn't be using fetch what's a better approach to this problem I'm having?
When I run this on an apache server (after building and deploying) I can get the fetches to work fine (apache recognizes the structure of the URL and hits it as I am expecting) and I hit the file no issues, but I need to be able to work in a local development environment and have the same functionality. The app will end up being deployed live on an apache server.
Any help would be greatly appreciated.
I knew after sleeping on this it would be very straight-forward... I simply had to move my models and controllers into the public directory for them to be accessible. I'll be putting in authentication to the models so that they can't be hit directly, but only through GET requests.
Why don't you just use something like ${baseUrl}/models/... ?
Also for solving browsers problem with fetch you can import the Polyfill or simply use axios (my choice)!
Maybe you can try to use ajax to get or post the data from server, just like this:
$.ajax({
url: '../models/overall-stats.php',
data: {
},
type: 'GET',
dataType : 'json',
success : function(res){
let obj = parseJSON(res)
}
})
or add this on top in your php file because the CORS :
header('Access-Control-Allow-Origin: *');

Mocha conflicting with Nimble (Async)

I'm using nimble.js in my app and mocha + chai for testing, but yesterday I found them to be possibly conflicting.
Basically, when I do a particular http request in my browser, I get
Unauthorized.
which is the correct response.
But using node's http module to do a http request using the same url, I get
not found
Which is confusing me.
I know the http request got the right url because I see it in the server console, even copy pasted it in my browser to be sure.
Additionally, I traced the code to the nimble.parallel function.
I have something like this:
// var _ = require('nimble');
_.parallel(
[
fetch_account(options)
, fetch_invoice(options)
, fetch_site(options)
, fetch_account_stats(options)
]
, render(res, subdomain)
);
// each of the function above returns another function, no simple API gotcha here
In the browser case, an error was correctly identified in a fetch function, then also in the render case.
In the mocha case, an error was correctly identified in a fetch function, but render was not executed. Hence, mocha must've did its own res.render("not found");
Any ideas?
I'm a f*cking idiot.
Forgot to set accept header.
But I'm still confused why I traced to same code but got different behavior.

Categories