解决方案
请参见******之间的代码!
后端-app.py:
from flask_cors import CORS
app = Flask(__name__)
***CORS(app, support_credentials=True)***
@app.route('/api/start', methods=['POST'])
***@cross_origin(supports_credentials=True)***
def dostuff_endpoint():
global doingstuff_active
if request.method == 'POST':
if not doingstuff_active:
doingstuff_active = True
return 'Doingstuff activated.'
else:
return 'Doingstuff already active.'
else:
return 'Invalid request method.'
// Some code
if __name__ == '__main__':
// Some code
***app.run(host='127.0.0.1', port=5000)***
前端- startButton.tsx:
'use client'
import { useEffect, useState } from 'react';
import axios from 'axios';
const StartButton = () => {
const [data, setData] = useState('');
const fetchData = async () => {
try {
const response = await axios.get('http://**127.0.0.1**:5000/api/dothat');
const newEntry = response.data.new_entry;
setData(newEntry || '');
} catch (error) {
console.log(error);
}
};
const handleClick = async () => {
try {
await axios.post('http://***127.0.0.1***:5000/api/dothing');
fetchData();
} catch (error) {
console.log(error);
}
};
return (
<div>
<button onClick={handleClick}>Start</button>
<p>{data}</p>
</div>
);
};
export default StartButton;
有许多与CORS相关的问题和解决方案,但在尝试了上述解决方案后,我仍然有问题。我将在本地运行这个应用程序,所以我不认为CORS是一个问题。有人能给我指个方向吗?TY!
我不想通过代理运行请求。
我尝试了以下提到的解决方案:(1)CORS error when making network call in useEffect in Next.Js,(2)Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?
CORS错误消息:
CORS策略阻止了从源“http://localhost:5000/api/start”访问XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。
后端-app.py:
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/api/start', methods=['POST'])
def dostuff_endpoint():
global doingstuff_active
if request.method == 'POST':
if not doingstuff_active:
doingstuff_active = True
return 'Doingstuff activated.'
else:
return 'Doingstuff already active.'
else:
return 'Invalid request method.'
// Some code
if __name__ == '__main__':
// Some code
app.run()
前端- startButton.tsx:
'use client'
import { useEffect, useState } from 'react';
import axios from 'axios';
const StartButton = () => {
const [data, setData] = useState('');
const fetchData = async () => {
try {
const response = await axios.get('http://localhost:5000/api/dothat');
const newEntry = response.data.new_entry;
setData(newEntry || '');
} catch (error) {
console.log(error);
}
};
const handleClick = async () => {
try {
await axios.post('http://localhost:5000/api/dothing');
fetchData();
} catch (error) {
console.log(error);
}
};
return (
<div>
<button onClick={handleClick}>Start</button>
<p>{data}</p>
</div>
);
};
export default StartButton;
1条答案
按热度按时间kqlmhetl1#
请确保配置CORS in your Next.js应用程序。