跨域AJAX请求是指从一个域名下的网页向另一个域名下的API端点发送的XMLHttpRequest请求。由于浏览器的同源策略(Same-Origin Policy)限制,这种请求默认会被阻止。
LinkedIn API支持CORS(跨域资源共享),但需要正确配置请求头:
fetch('https://api.linkedin.com/v2/me', {
method: 'GET',
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json',
'X-Restli-Protocol-Version': '2.0.0'
},
credentials: 'include'
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
如果直接跨域请求仍有问题,可以设置服务器端代理:
// 前端代码
fetch('/api/linkedin-proxy', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
endpoint: '/v2/me',
method: 'GET'
})
})
.then(response => response.json())
.then(data => console.log(data));
// Node.js代理服务器示例
const express = require('express');
const axios = require('axios');
const app = express();
app.post('/api/linkedin-proxy', async (req, res) => {
try {
const { endpoint, method } = req.body;
const response = await axios({
method: method || 'GET',
url: `https://api.linkedin.com${endpoint}`,
headers: {
'Authorization': `Bearer ${process.env.LINKEDIN_ACCESS_TOKEN}`,
'X-Restli-Protocol-Version': '2.0.0'
}
});
res.json(response.data);
} catch (error) {
res.status(500).json({ error: error.message });
}
});
如果API支持JSONP,可以使用这种方式:
function handleLinkedInResponse(data) {
console.log(data);
}
const script = document.createElement('script');
script.src = 'https://api.linkedin.com/v2/me?format=jsonp&callback=handleLinkedInResponse';
document.body.appendChild(script);
Authorization
和X-Restli-Protocol-Version
X-Restli-Protocol-Version: 2.0.0