简体   繁体   中英

How to execute Python code within React app?

I need to parse a web page and display a result in React component. Due to CORS, I'm unable easily access that page from my application, while python makes this in a few lines.

As I read in multiple similar answers, the key is to make ajax request to python code.

So, what I'm doing:

axios.post('../../assets/wordnik.py').then(res => console.log(res))

Plain and simple, though I get the following error: 在此处输入图片说明

So, how can I fix this and what is wrong exactly?

UPD. Python code

from bs4 import BeautifulSoup
from urllib.request import urlopen

url = "https://www.wordnik.com/randoml"
f = urlopen(url)
soup = BeautifulSoup(f, "html.parser")
h1s = soup("h1")
h1 = h1s[0].getText().strip()
print(h1)

Just dropping a python script in your react app source doesn't magically turn it into an API entry point. The script has to be executed by a python process, and you must have an HTTP server mapping this process to an url, passing the request to the process and forwarding the response. Plain, basic HTTP backend programming stuff actually.

The prefered way to server a python backend app is the wsgi protocol, which is supported one way or another by the main HTTP servers (apache, nginx etc). You can write your script directly to the wsgi spec, or use an existing wgsi framework ( flask comes to mind for simple, lightweight apps like your).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM