简体   繁体   中英

Send ajax request to remote node.js server

I had simple nodejs server(CORS included) :

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);
});

and simple ajax request

 $.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);
                }
            });

But i had an error 404 that localhost:8001/getSockets not found

A 404 error means the URL doesn't exist or it can't access it

change this line:

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

to this:

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

You are only allowing ajax requests to access resource on port 8000 you should change it to 8001 or just not specify a port.

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

Also please see using CORS with ports

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM