我正在尝试通过向https://www.wunderlist.com/oauth/access_token发送包含所需JSON数据的POST请求来在我的应用中交换访问令牌的授权码。但是,该请求获得404:
XMLHttpRequest无法加载https://www.wunderlist.com/oauth/access_token。对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许原点“http://localhost:3000”访问。响应的HTTP状态代码为404.
如果我与Postman尝试完全相同的请求,我会毫无问题地获得访问令牌。我也在我的服务器上启用了CORS(使用Express),它在同一个端口上处理App和API,但不知怎的,它不起作用:(
server.js
// Get dependencies
var express = require('express');
var path = require('path');
var cors = require('cors');
var http = require('http');
var bodyParser = require('body-parser');
require('dotenv').config();
var mongoose = require('mongoose');
mongoose.connect(process.env.MONGODB_URI);
var conn = mongoose.connection;
conn.on('connected', () => {
console.log('Connected to database');
});
conn.on('error', console.error.bind(console, 'connection error:'));
// Get the API routes
var api = require('./server/routes/api');
var app = express();
// CORS middleware
app.options('*', cors());
// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist')));
// Set the api routes
app.use('/api', api);
// Catch all other routes and return the index file
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});
/**
* Get port from environment and store in Express.
*/
var port = process.env.PORT || '3000';
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, () => console.log(`Server running on ${port}`));
wunderlist.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class WunderlistService {
constructor(private http: Http) { }
getAccessToken(code: string) {
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post('https://www.wunderlist.com/oauth/access_token', {
"client_id": "myclientidhere",
"client_secret": "myclientsecrethere",
"code": JSON.stringify(code)
}, {headers: headers})
.map(res => res.json());
}
}
编辑:
我认为这个问题与 server.js 文件没有任何关系,而是与Wunderlist服务本身的帖子请求有关。我试图使用从Postman获得的访问令牌向Wunderlist API发布帖子请求,一切都运行得很好。
当我尝试发布到https://www.wunderlist.com/oauth/access_token时,是否有人知道可能导致404错误的原因?
在上述错误消息之上,我也收到错误消息 OPTIONS https://www.wunderlist.com/oauth/access_token 404(Not Found),这可能有帮助吗? 谢谢,格奥尔格