简单测试CORS

测试脚本

1
2
3
4
5
6
7
8
9
10
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
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

image-20220616022517361

测试脚本2

1
2
3
4
5
6
7
8
9
10
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
// 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' })
}

测试脚本3

1
2
3
4
5
6
7
8
9
10
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
11
12
13
14
15
16
17
18
19
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!' })
}

image-20220616023424123

参考

https://nextjs.org/docs/api-routes/api-middlewares

作者

Terwer

发布于

2022-06-16

更新于

2022-06-16

许可协议

评论