简单测试CORS

Terwer...小于 1 分钟实用技巧经验分享corsxhr

测试脚本

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();

结果

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
image-20220616022517361

测试脚本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();

代码如下

// 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

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();

修改代码之后,正常

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
image-20220616023424123

参考

https://nextjs.org/docs/api-routes/api-middlewaresopen in new window

评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.14.9