我正在学习JavaScript&阿贾克斯&的NodeJS。
我正在尝试构建一个显示服务器字符串的网页。
服务器代码:
#include <iostream>
#include <string>
#include <vector>
#include <memory>
class employee
{
std::string NAME;
int NUM;
int Enum = 0;
public:
std::vector<std::shared_ptr<employee>> childs;
employee(std::string name, int num) :NAME(name), NUM(num)
{
childs.resize(num);
}
std::string getName()
{
return NAME;
}
int getNum()
{
return NUM;
}
void setEnum(int num)
{
Enum = num;
}
int getEnum()
{
return Enum;
}
};
class eTree
{
private:
std::shared_ptr<employee> proot;
public:
eTree(employee node) { proot = std::make_shared<employee> (node); }
void buildTree(std::shared_ptr<employee> parent);
std::shared_ptr<employee> getP() { return proot; }
std::shared_ptr<employee> buildChilds(employee &parent, int i);
};
void eTree::buildTree(std::shared_ptr<employee> parent)
{
int num = parent->getNum();
if (num != 0)
{
for (int i = 0; i < num; i++)
{
(*parent).childs[i] = buildChilds(*parent, i);
std::cout << (*parent).childs[i] << std::endl;
buildTree((*parent).childs[i]);
}
int eNum = (*parent).getNum();
for (int j = 0; j < num; j++)
{
eNum += (*((*parent).childs[j])).getEnum();
}
(*parent).setEnum(eNum);
}
}
std::shared_ptr<employee> eTree::buildChilds(employee &parent, int i)
{
std::string name;
int num;
std::cout << "Enter the name of " << parent.getName() << "'s " << i + 1 << " child:" << std::endl;
std::cin >> name;
std::cout << "How many employee work for " << parent.getName() << "'s " << i + 1 << " child:" << std::endl;
std::cin >> num;
// employee child(name, num);
std::shared_ptr<employee> pchild (new employee(name, num));
// std::shared_ptr<employee> pchild = std::make_shared<employee>(child);
return pchild;
}
void more3(employee parent);
void noChild(employee parent);
int main()
{
using namespace std;
std::string name;
cout << "Enter the employee's name: ";
cin >> name;
int num;
cout << "How many employees work for him/her: ";
cin >> num;
employee root(name, num);
shared_ptr<employee> proot = make_shared<employee> (root);
eTree tree(root);
tree.buildTree(proot);
cout << tree.getP()->childs[0] << endl;
cout << tree.getP()->childs[1] << endl;
return 0;
}
客户端代码:
var express = require('express');
var app = express();
app.get('/sms', function (req, res) {
console.log("Got request: " + req);
res.send('Hello World');
console.log("Send result");
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Listening at http://%s:%s", host, port)
})
点击按钮后,我得到一个空字符串。
这里的日志: 状态:1状态:0 Ajax1.html:1 XMLHttpRequest无法加载http://127.0.0.1:8081/sms。 No&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上。起源&#39; null&#39;因此不允许访问。 Ajax1.html:28状态:4状态:0 Ajax1.html:35得到结果:
为什么我得到一个空字符串?我错过了什么? 感谢
答案 0 :(得分:1)
您的客户端代码和服务器代码必须位于相同的源(相同的主机名,相同的端口)才能发出AJAX请求。
127.0.0.1 无法将AJAX请求发送到127.0.0.1:8081。
要修复,请将node.js反向代理到相同的主机名(推荐),或者在node.js中设置Access-Control-Allow-Origin。