Js:
fetch('app.py').then(res=>res.text()).then(data=>console.log(data));
Python:
print('helloworld')
console.log()
shows print('helloworld')
instead of helloworld
Am I not getting something here? I want the Python code to return "helloworld" to the browser's console, but instead it sends the sourcecode. Same with php(note that php --version
in cmd sends PHP Warning:'vcruntime140.dll' 14.0 is not compat..
). But python appears to have no issues on my pc.
Is my problem in my code? Or what is necessary for the app.py or app.php to run when I fetch it?
Hi, I'm a young programmer, have been trying to add scripts to my server to let client-side send data to server-side, in which server-side's job is to receive and write data into files to my server. Thanks
CodePudding user response:
All that code is doing is fetching a local file (app.py) and then printing its contents to the browser console. This isn't how api's work. You can create an api endpoint in Flask (a Python library for writing apis) that will print helloworld to a separate (the server) console, or return it as data. Follow this guide to get you started (you may want to follow the installation instructions first - link on the page) https://flask.palletsprojects.com/en/1.1.x/quickstart/ Your fetch statement will look like this fetch('/').then(res=>res.text()).then(data=>console.log(data));
your app.py will look as follows:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
I am not familiar with php so afraid I can't give you pointers there.
CodePudding user response:
You cannot run Python or PHP files on the client side, this has to be done on the backend. For Python you need to run a script (server) that listens for incoming requests, and on that send a response. The same applies to PHP, you can use web servers like Apache, Nginx, Lighttpd and more to run php.
Seems like you have a static server for files fetching, but again, you cannot request the file and expectate it to run.