API调用失败,CORS,nginx已配置的解决方法取决于具体的情况和代码实现。下面是一些常见的解决方法和代码示例:
# nginx配置
location /api {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
add_header 'Access-Control-Max-Age' 1728000;
add_header 'Content-Type' 'text/plain charset=UTF-8';
add_header 'Content-Length' 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
# 其他nginx配置...
}
# Python Flask示例
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/api/data', methods=['GET', 'POST'])
def get_data():
response = jsonify({'message': 'API调用成功'})
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
response.headers.add('Access-Control-Allow-Headers', 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range')
return response
if __name__ == '__main__':
app.run()
// JavaScript示例
const url = 'https://api.example.com/data';
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('API调用失败');
}
return response.json();
})
.then(data => {
// 处理返回的数据
})
.catch(error => {
console.error(error);
});
请注意,这些解决方法和示例仅供参考,具体的实现可能因编程语言、框架和服务器配置而有所不同。您需要根据自己的代码和环境进行适当的调整。
下一篇:API调用失败,返回401错误。