简单测试CORS
# 测试脚本
const xhr = new XMLHttpRequest();
const url = 'https://xmlrpc.terwergreen.com/api/xmlrpc';
xhr.open('GET', url);
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText)
}
};
xhr.send();
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
结果
Access to XMLHttpRequest at 'https://xmlrpc.terwergreen.com/api/xmlrpc' from origin 'https://nextjs.org' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
_app-4ccd7c9a287b6dc7.js:1
GET https://xmlrpc.terwergreen.com/api/xmlrpc net::ERR_FAILED 200
1
2
3
2
3
# 测试脚本2
const xhr = new XMLHttpRequest();
const url = 'https://xmlrpc.terwergreen.com/api/hello';
xhr.open('GET', url);
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText)
}
};
xhr.send();
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
代码如下
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
export default function handler(req, res) {
res.status(200).json({ name: 'John Doe' })
}
1
2
3
4
5
2
3
4
5
# 测试脚本3
const xhr = new XMLHttpRequest();
const url = 'https://xmlrpc.terwergreen.com/api/cors';
xhr.open('GET', url);
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText)
}
};
xhr.send();
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
修改代码之后,正常
import Cors from 'cors'
import initMiddleware from '../../lib/init-middleware'
// Initialize the cors middleware
const cors = initMiddleware(
// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options
Cors({
// Only allow requests with GET, POST and OPTIONS
methods: ['GET', 'POST', 'OPTIONS'],
})
)
export default async function handler(req, res) {
// Run cors
await cors(req, res)
// Rest of the API logic
res.json({ message: 'Hello Everyone!' })
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 参考
https://nextjs.org/docs/api-routes/api-middlewares (opens new window)
编辑 (opens new window)
上次更新: 2023/09/19, 13:33:19