Webpack and React Image Not Found - javascript

I have looked at so many different resources (some not linked, and this one being the closest to my problem). None of them seem to solve my issue.
I'm brand new to both React and Webpack. I found this tutorial and followed it to create a basic website.
However, I'm having issues displaying images. Instead of displaying the image, I get a "broken file" image and the console says GET http://127.0.0.1:5000/public/images/smiley.png 404 (NOT FOUND)
I have installed the Webpack image loader and I am using require in my React code. It looks like webpack is finding the image because if I change the name of the image I get an error like Uncaught Error: Cannot find module '../images/smiley.png' which crashes the whole website instead of the 404 error.
This is my folder structure:
When I run the project with npm run watch and python server.py (from static folder and server folders respectively), a public folder with smiley.png inside of it appears inside of the dist folder.
I have a hunch that the issue is that my Flask is configured in such a way that it does not respond the request because it thinks the public folder is off limits. But that's just a hunch, and I don't know how to fix it if that's the case.
My code can be found here. Any help would be appreciated.
EDIT:
Following my hunch, I added the following to my server.py:
#app.route("/public/<path:path>")
def get_public_file(path):
print("getting something from public: {}".format(path))
return send_from_directory("public", path)
But that also did not work - I am still getting a 404.
EDIT 2:
Thanks to #Joost, we found out that using app = Flask(__name__, static_folder="../static", template_folder="../static") puts the image correctly at http://127.0.0.1:5000/static/images/smiley.png.
However, this then causes Flask to not be able to figure out where bundle.js is, since it's located inside the dist folder.
Adding in
#app.route("/dist/<path:path>")
def get_dist_file(path):
print("getting something from dist: {}".format(path)) # this ran
return send_from_directory("dist", path)
to server.py did not help - I still get GET http://127.0.0.1:5000/dist/bundle.js net::ERR_ABORTED 404 (NOT FOUND) in the inspector.
So now the trick is to figure out how to keep the smiley face served, and have flask serve the bundle.js file as well.
EDIT 3:
I just discovered a really sketchy way of getting it to work, so sketchy that I'm not even going to post it as an answer because I want something that's less sketchy.
Using #Joost's app = Flask(__name__, static_folder="../static", template_folder="../static") and adding the following to server.py worked.
#app.route('/<path:path>')
def static_file(path):
print("getting static file {}".format(path))
if path.startswith("public/"):
path = "dist/" + path
print("in public folder; path changed to: {}".format(path))
return app.send_static_file(path)
The issue with this solution is that I really shouldn't be using send_static_file since it's extremely insecure, and that including an if statement like that seems prone to many errors. A different solution would be appreciated.

I kept overlooking where the app was running from, sorry about that.
By far the easiest solution is to set you static folder to a different folder:
app = Flask(__name__, static_folder='../static')
I just tried it, and this should work without a problem.
You can find your file here:
http://127.0.0.1:5000/static/images/smiley.png
Your bundle file will be here:
http://127.0.0.1:5000/static/dist/bundle.js
You're getting a template error because you don't have a template folder, which is normally called tempates. So make a subfolder called templates in your server folder. Then, don't specify the template_folder argument in the app = Flask(..) line, but keep it app = Flask(__name__, static_folder='../static').
If, for some reason, you want to seperate your static from your public files and have a /public route as well, you might want to try the following approach:
#app.route("/public/<path:path>")
def get_public_file(path):
full_path = os.path.join('../static/dist/public/', path)
head, tail = os.path.split(full_path)
return send_from_directory(head, tail)
You can then access the smiley in the fullstack_template/static/dist/public/images/smiley.png by going to http://127.0.0.1:5000/public/images/smiley.png.

Related

Jekyll Converters::Scss build issue: No such file or directory # dir_chdir - /github/workspace/docs

I keep getting this error when I try to publish a site to GitHub pages.
Conversion error: Jekyll::Converters::Scss encountered an error while converting 'assets/css/style.scss':
19
No such file or directory # dir_chdir - /github/workspace/docs
When I try to change the folder to root, it publishes the readme.md file. When I change it to doc, I get this error.
The file runs fine locally. I don't know what the problem is. I searched online but did not find a solution that helps. Any help works.
The error is on my main branch when I try to publish it.
Links to the repo and the error on GitHub:
https://github.com/Rsmdo/dadport2
https://github.com/Rsmdo/dadport2/tree/main
I tried making a new repo but this did not solve the issue, also I went through the code to see if there were any parsing errors but there were none.
https://talk.jekyllrb.com/t/cannot-deploy-site-via-github/6883/11 says that "Jekyll can’t find the files the theme uses". The page also suggests using root instead of docs or any folder.
There are options to set the directory where Jekyll writes files to and reads file from, for example: bundle exec jekyll s -s /docs, which leads to errors in my case due to the non-existing path based on the root path (the path can also be relative I guess).
See Source: /docs, the other path do not show the docs path though.
PS C:\Users\User\usr.github.io> bundle exec jekyll s -s /docs
Configuration file: none
Source: /docs
Destination: C:/Users/User/usr.github.io/_site
Incremental build: disabled. Enable with --incremental
Generating...
Error reading file C:/Users/User/usr.github.io/_layouts/archive.html: No such file or directory # rb_sysopen - C:/docs/Users/User/usr.github.io/_layouts/archive.html
This may help:
https://jekyll.one/pages/public/manuals/jekyll/user_guide/configuration/
https://github.com/burtlo/jekyll-core/blob/master/site/docs/configuration.md

How can I properly use the res.sendFile for my MERN APP, I get an error every time I refresh it

So I created a post previous day and deleted it because it's unproper and also unclear, so right now, I'll try to write it properly.
So I created a MERN app using render.com, but the problem is every time I refresh the the webpage, I get an error / not found. Example. I went to a specific user id , I can view his the profile but once I refresh/reload, it gets an error. So I created a two separate folder and two different GitHub repo.
I uploaded the front end as a static website in render.com
Github: Front Site
Website Front Website
So for the backend, I follow this thread and Why deployed create-react-app returns 404 error upon reload?. But I don't know how can I properly use res.sendFile because I'm using a different root directory as well as different github repo.
Github : https://github.com/cruz-emman/back
Website: https://mern-tua-ebenta.onrender.com/
I tried to use this, and I admit that I'm doing it wrong because I don't know how can I do it.
app.use(express.static(path.join(__dirname,'../client/build')));
app.get('*', (req,res) => res.sendFile(path.resolve(__dirname,'../', 'client','build','index.html'))
EDIT: TYPO
After trial and error, I finally solved the answer, so what I did here is merge the two folders.
After putting it in a single directory, I run npm run build for client folder. After that, I put this code inside index.js
const __dirname = path.resolve()
app.use(express.static(path.join(__dirname, '/client/build')));
app.get("*",(req,res) => {
res.sendFile(path.join(__dirname, '/client/build/index.html'));
})
After that, I push it to a new git repository, and run web service for render.com

Can't Load Models for face-api.js

I don't understand how to load the "models" so that the client side of my React web app can start analyzing images. I don't even really understand what a "model" is.
I started by doing npm i face-api.js.
Then, I imported it into my SignUp component by typing import * as faceapi from 'face-api.js' at the top.
In my componentDidMount() function, I put the following code:
faceapi.nets.ssdMobilenetv1.loadFromUri('/models').then(result => {
console.log(result);
}).catch(error => {
console.log(error)
})
That gives me the following error:
SyntaxError: "JSON.parse: unexpected character at line 1 column 1 of the JSON data"
So I tried looking for a "models" directory in the face-api.js directory, but couldn't find anything. Then I went back to the Github and found a "weights" folder (which I read are related to models). I downloaded it, and put it's contents in a "models" folder near my SignUp component (see attached pic). Still the same error.
Ultimately, all I want to do is know whether a user uploads a pictures containing a face. Any face. I don't need anything more than that. What am I doing wrong?
For my example using VueJs i added the models in the public / dist directory and i followed the directions for the github examples.
Promise.all([
faceapi.nets.faceRecognitionNet.loadFromUri('/models'),
faceapi.nets.ssdMobilenetv1.loadFromUri('/models'), faceapi.nets.faceLandmark68Net.loadFromUri('/models'),
])
.then(async () => {//some code goes here})
Sample I used
When you run this :
faceapi.nets.ssdMobilenetv1.loadFromUri('/models')
It looks for models in the the public/models directory but it will only load the json file.(Verify this by checking the Network Tab in the browser). It might run on your local machine but will fail when you deploy.
In our case it failed in production because it needed the data from *_shard1 file but our server was unable to fetch those file without any extension.
To solve this issue we suffixed all those file with ".shard" extension and changed the path in the respective json file :
From :
...,"paths": ["file_name_shard1"]}]
To:
...,"paths": ["file_name_shard1.shard"]
Found this solution here: https://github.com/justadudewhohacks/face-api.js/issues/131
Smarann Educations's reply above is very useful, except that I made the following changes to get mine to work on the production server:
Instead of ".shard" extension, as advised by Smarann Educations, I input a ".bin" extension to the shard files. And, similarly, in the corresponding json files, I updated the paths to ".bin" instead of ".shard", as suggested by Smarann Educations. This ".bin" suggestion is in one of the comments at the link that Smarann Educations provided in his reply
I modified all the loadFromUri('/models') statements to loadFromUri('./models') - So, replaced '/models' with './models' (Notice the dot before the slash)
You can use loadFromDisk instead of loadFromUri.
or
You can change the model's filename extension to .dir instead of .json.
I had the same issue in react, but in development and productions servers. So, to fix it locally (on localhost), just put the models folder in the public folder.
To fix in on server, you should put the models folder into build/static.
So I added in package.json script:
"replace_models":
"node -e \"const fs = require('fs-extra');
fs.copy('./build/models', './build/static/models').then(
() => {fs.removeSync('./build/models');
return console.log('success!')}
).catch(err => console.error(err))\"
"
And then:
"build": "react-scripts build && npm run replace_models"

Qt Creator import file not found

I am trying to learn Qt QML with Qt Creator. I want to put my javascript functions into a seperate file and 'import' it into the qml world. Have got the code as below for testing how this works.
Trouble is I get the following error when I run the project in Creator...
> Starting
> /home/dev/docs/projects/Qt/build-XmlModelView-Desktop-Debug/XmlModelView...
> QML debugging is enabled. Only use this in a safe environment.
> QQmlApplicationEngine failed to load component qrc:/main.qml:5 Script
> qrc:/MyFuncs.js unavailable qrc:/MyFuncs.js:-1 File not found
I have watched videos and followed the Qt online docs and looked at others code, but I can't see what is wrong.
I can only guess that some sort of path is not set correctly, but in the docs it says the default path includes the directory that the QML file is in. My .js and .qml files are in the same directory. Also I tried editing the resource file, but that crashed it completely.
I tried moving the .js file to different locations, absolute path in the import statement. My eyeballs are starting to fall out now.
Oddly IT DOES WORK if I use qmlscene to run main.qml
Can anybody help? Here is my code...
main.qml file:
import QtQuick 2.3
import QtQuick.Window 2.2
import "MyFuncs.js" as MyFuncs
Window {
id: window1
visible: true
Rectangle {
id: contentArea
MouseArea {
id: mouseArea1
anchors.fill: parent
onClicked: {
MyFuncs.myfunc();
}
}
}
main.cpp file:
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
MyFuncs.js File:
function myfunc() {
console.log("function was called")
}
Thanks for any help. Lost a whole day, just don't know where to go on.
NOTE:
You can probably just add the JavaScript file to the resources--and then when your project hits complexity where you don't want to recompile for each little change you can do what I did here below:
You're loading the file via qrc:/MyFuncs.js which is the file path to the resource. The problem is that the JavaScript file (likely) was not copied or isn't on your path. (It means you need to bundle it) depending on the path of your scene you might have it show up. As an example here I need to copy my JavaScript and QML to the build directory which is just annoying:
Here's an example of my config file for a moderately sized project:
CONFIG += c++11
# Add more folders to ship with the application, here
folder_qml.source = qml
folder_qml.target = /
folder_js.source = js
folder_js.target = /
folder_img.source = img
folder_img.target = /
folder_icon.source = icon
folder_icon.target = /
DEPLOYMENTFOLDERS += folder_qml folder_js folder_img folder_icon
Notice the REALLY weird syntax here: this copies the js, qml, icon, and img folders,to / in the build which you would think dumps those files on the root. Think again! The build directory looks like this:
+ debug
+ icon //I added this explicitly
+ img //I added this explicitly
+ js //I added this explicitly
+ qml //I added this explicitly
+ release
Makefile
Makefile.Debug
Makefile.Release
Now my application can correctly reference the files as they exist on the path. When running inside the IDE (depending on the setup) you might have the files available to you, you might not.
Here's a snippit from my main.qml:
import QtQuick 2.2
import QtQuick.LocalStorage 2.0
import QtQuick.Controls 1.0
import QtQuick.Layouts 1.1
import com.lightassistant 1.0
import "qrc:/js/lightassistant.js" as LA;
import "qrc:/js/statics.js" as Statics
To prove a point here:
If I change the qrc:/js/statics.js to qrc:/nope/js/statics.js here's the error:
` qrc:/nope/js/statics.js: File not found`
or
` qrc:/statics.js: File not found`
Now from inside the IDE things should be fine as it runs the executable inside the source code. The problems listed above here are in regards to deployment and there are MANY ways around that. I prefer this so I can run batch commands, you could also use [OS]qtdeploy tools and specify some paths to get around it.
This technique prevents the resource files from being recompiled every time you make a chance which can add HOURS to your workday if you're testing the QML. Copying files is fast and doesn't require bundling the resource file.
I hope this helps, I too, lost a few days to figuring this out a year and half ago.
I'm still not sure why my import needed the file to be in 'Resouces', others I've seen on youtube appeared to work without that. However, the code works now that I have added the .js file to resources by right clicking, not on resources but on the / folder within resources. Why didn't I try that before.
Thanks to both for help.

Using require when electron app is packaged in an asar

In my main.js, I have:
var mainFrm = require('./MainFrm');
This works fine except when the application is packaged as an asar file. I get a 'Cannot find module' error.
The documentation states to use the following:
require('/path/to/example.asar/dir/module.js');
I tried that but got the same error. Where does the path begin when using the above? Does path start with electron.exe is? Also, if I use require('/resources/app.asar/MainFrm.js') what path do I use for OS X apps since the Resources folder is in a different location? What path should I use during development/debugging (i.e. not inside of an asar)
I think you may have 2 issues. First, you may need to be explicit about the file extension, thus looking for MainFrm.js, not just MainFrm. Second, try using resolve to determine the name relative to the current directory.
One way to resolve this is to resolve the path at runtime, like this:
var mainFrm = require("path").resolve(__dirname, "./MainFrm.js");
Try some combinations of that and see if it doesn't help.

Categories

Resources