将ajax请求发送到远程node.js服务器

时间:2017-08-23 08:02:21

标签: javascript node.js ajax cors

我有简单的nodejs服务器(包括CORS):

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 8001;
http.listen(port,function () {
    console.log('listening on:'+ port);
});
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    res.setHeader('Access-Control-Allow-Credentials', true);
    next();
});
app.post('/getSockets', function (req,res,next) {
   console.log(req.body);
});

和简单的ajax请求

 $.ajax({
                type: "POST",
                url: "http://localhost:8001/getSockets",
                data: "Hello world",
                success: function (data, textStatus, XMLHttpRequest) {
                    console.log(data);
                    console.log("success!");
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest.status);
                }
            });

但我有一个错误404,localhost:8001 / getSockets not found

2 个答案:

答案 0 :(得分:2)

404错误表示URL不存在或无法访问

更改此行:

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');

到此:

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8001');

答案 1 :(得分:1)

您只允许ajax请求访问端口8000上的资源,您应该将其更改为8001或者不指定端口。

res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8000');

另请参阅 using CORS with ports