我想创建一个 Gatsby 应用程序,调用我的 Azure SQL 数据库的 REST API 来读取数据。 在我部署的 Azure 静态 Web 应用程序 (SWA) 中,访问工作正常,但在“Gatsby 开发”模式下则不然。
这是我的 GET 请求:
fetch('https://example.com/data-api/rest/blogs')
我在 gatsy 开发中收到以下错误消息:
Access to fetch at 'https://example.com/data-api/rest/blogs' from origin 'http://localhost:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
还将“no-cors”模式添加到我的 GET 请求中也没有帮助。
fetch('https://example.com/data-api/rest/blogs/', { method: 'GET', mode: "no-cors", headers: { "Content-Type": "application/json" }
您遇到的错误是由于尝试从本地 Gatsby 开发环境访问 Azure SQL 数据库 REST API 时出现 CORS(跨源资源共享)问题。确保添加 CORS。
我使用以下命令创建了一个简单的 Gatsby 应用程序:
npx gatsby new static-web-app
要添加 CORS(跨源资源共享),请使用
cors
中间件:
npm install cors
package.json
:
"dependencies": {
"gatsby": "^5.13.3",
"gatsby-plugin-image": "^3.13.1",
"gatsby-plugin-manifest": "^5.13.1",
"gatsby-plugin-sharp": "^5.13.1",
"gatsby-source-filesystem": "^5.13.1",
"gatsby-transformer-sharp": "^5.13.1",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"engines":{
"node":">=18.0.0"
},
staticwebapp.config.json:
{
"navigationFallback": {
"rewrite": "index.html"
}
}
蔚蓝: Azure SQL:
app.use(cors()); // Use the cors middleware
// Server and database configuration
const config = {
server: process.env.AZURE_SQL_SERVER,
port: process.env.AZURE_SQL_PORT,
database: process.env.AZURE_SQL_DATABASE,
user: process.env.AZURE_SQL_USER,
password: process.env.AZURE_SQL_PASSWORD,
options: {
encrypt: true,
trustServerCertificate: false,
connectionTimeout: 30000,
requestTimeout: 30000 // optional request timeout in milliseconds
}
};
// Endpoint to fetch persons
app.get('/', async (req, res) => {
try {
const pool = await sql.connect(config);
const result = await pool.request().query('select * from [dbo].[employees]');
res.status(200).json(result.recordset);
} catch (error) {
console.error('Error reading data from database:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
蔚蓝: