【发布时间】:2018-02-18 02:26:33
【问题描述】:
我有一个这样的 restify 设置:
var restify = require('restify');
const server = restify.createServer();
//server.use(restify.plugins.acceptParser(server.acceptable)); // [1]
server.use(restify.plugins.queryParser());
server.use(restify.plugins.bodyParser());
server.use(function(req, res, next) {
console.log(req); // <-- Never see the POST from React here
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', '*');
res.setHeader('Access-Control-Allow-Methods', '*');
next();
});
我定义了一堆 GET 和 POST 路由,到目前为止它工作得非常好。我从一个 Android 应用程序、Python 脚本调用服务器,并简单地使用 curl 进行测试。完全没有问题。整洁!
但是,现在我已经使用 React 实现了一个 Web 应用程序,并希望使用 axios 包向 restify API 发出请求。 GET 请求很好,所以我排除了 URL 中的任何拼写错误或类似的东西。
但是像下面这样的 POST 请求不起作用:
var data = {"test": "hello"};
axios.post("http://.../api/v1/message/question/public/add", data)
.then(function (response) {
console.log("Test question sent!");
})
.catch(function (error) {
console.log(error);
});
当我查看浏览器开发者工具时,我可以看到浏览器正在尝试向该 URL 发出 OPTIONS 请求(而不是 POST)。我认为,根据我的阅读,这是因为浏览器正在发出“预检请求”。问题是我收到405 Method Not Allowed 错误:
Request URL: http://.../api/v1/message/question/public/add
Request method: OPTIONS
Remote address: ...
Status code: 405 Method Not Allowed
Response headers (178 B)
Server: restify
Allow: POST
Content-Type: application/json
Content-Length: 62
Date: Sat, 09 Sep 2017 08:16:32 GMT
Connection: keep-alive
Request headers (485 B)
Host: ...
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linu…) Gecko/20100101 Firefox/55.0
Accept: text/html,application/xhtml+xm…plication/xml;q=0.9,*/*;q=0.8
Accept-Language: en-ZA,en-GB;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://...
DNT: 1
Connection: keep-alive
但是为什么呢?我允许所有Access-Control-Allow-Methods 重新调整。一切正常,除了来自POST 请求并且只有当它们来自浏览器(使用 React Web 应用程序)时。我认为是因为OPTIONS 请求,但我不知道如何处理。
顺便说一下JSON.stringify(data),POST 请求可以通过,但 API 需要 Json 而不是字符串。而且由于使用所有其他方式它工作得很好,我不想仅仅为了适应这个问题而更改 restify 代码。
[1] 如果我使用这一行,我会收到以下错误:AssertionError [ERR_ASSERTION]: acceptable ([string]) is required at Object.acceptParser (/home/bob/node_modules/restify/lib/plugins/accept.js:30:12)
【问题讨论】:
标签: json reactjs cors axios restify