首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >发布请求,以便使用Fetch API重新定位

发布请求,以便使用Fetch API重新定位
EN

Stack Overflow用户
提问于 2017-09-15 15:50:52
回答 1查看 1.5K关注 0票数 1

我很难理解为什么Fetch API不允许我向restify服务器发送POST请求。

我有一个基本的restify服务器,它的路由可以在/login上接收POST请求。

如果使用Postman或HTTPRequester进行测试,此路由完全可以正常工作,但是当我使用fetch API在浏览器应用程序上测试它时,我会得到以下错误(在Chrome中):

代码语言:javascript
运行
复制
OPTIONS http://localhost:1337/login 405 (Method Not Allowed)

Fetch API cannot load http://localhost:1337/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 405. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

两个问题

  1. 我在请求中特别使用了POSt方法,那么为什么突然使用选项呢?
  2. 我已经在服务器上设置了Access-Control-Allow-Origin: *

编辑:我使用restify v5.2.0

我的服务器应用程序

代码语言:javascript
运行
复制
const restify = require('restify');
const app = restify.createServer({
    'name': 'API Token Test',
    'version': '1.0.0'
});

app.use(restify.plugins.acceptParser(app.acceptable));
app.use(restify.plugins.bodyParser());
app.use(restify.plugins.jsonp());

app.use((req, res, next) => {
	res.header('Access-Control-Allow-Origin', '*');
	res.header('Access-Control-Allow-Headers', 'X-Requested-With');
	return next();
});

app.post('/login', (req, res) => {
    db.execute('SELECT idusers, password FROM users WHERE username = ?', [req.body.username], (selError, rows) => {
        if (passwordHash.verify(req.body.password, rows[0].password)) {
            crypto.randomBytes(256, (err, buf) => {
                if (err) return res.status(500).end();
                else {
                    const token = buf.toString('hex');
                    db.execute('INSERT INTO accesstokens SET userid = ?, token = ?', [rows[0].idusers, token], (insError) => {
                        if (insError) return res.status(500).end();
                        else return res.send({ "AccessToken": token });
                    });
                }
            });
        } else {
            res.status(401).end();
        }
    });
});

app.listen(1337);

(我忽略了mysql的内容和密码/密码散列-requires,它们与问题无关)

和我的客户端脚本

代码语言:javascript
运行
复制
(() => {
    document.addEventListener('DOMContentLoaded', () => {
        const form = document.querySelector('.loginForm');

        form.onsubmit = () => {
            const data = JSON.stringify({
                'username': form.username.value,
                'password': form.password.value
            });

            let headers = new Headers();
            headers.set('Accept', 'application/json');
            headers.set('Content-Type', 'application/json');
            headers.set('Content-Length', data.length);


            fetch('http://localhost:1337/login', {
                'method': 'POST',
                'headers': headers,
                'mode': 'cors',
                'cache': 'default',
                'body': data
            })
                .then((result) => result.json())
                .then((data) => {
                    console.log(data);
                    localStorage.setItem('token', data);
                })
                .catch((err) => {
                    console.log(err);
                });

            return false;
        };
    });
})();

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-09-15 16:22:47

从restify v5.x开始,所有的CORS支持都被移到了这个模块

安装restify-cors中间件并将以下内容添加到我的应用程序中是有效的:

代码语言:javascript
运行
复制
const corsMiddleware = require('restify-cors-middleware');
const cors = corsMiddleware({
    'origins': ['*']
});
app.pre(cors.preflight);
app.use(cors.actual);
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46243393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档