仅在NodeJS中更改URL

时间:2017-01-25 22:37:34

标签: javascript node.js

我的服务器回调中有以下代码段:

switch (request.url) {
    case "/somescript" :
        response.writeHead(200, {"Content-Type": "text/javascript"});
        response.write(somescript);
        break;      
    default :
        response.writeHead(200, {"Content-Type": "text/plain; charset=UTF-8"});
        response.write(html);
}
response.end();

当我运行服务器时,当我输入此内容时:

localhost:3000
浏览器上的

,如何让它自动更改为:

localhost:3000/changed

仅使用Node.js(在我的switch语句的默认部分中)?

1 个答案:

答案 0 :(得分:1)

只需将response.writeHead(301, {"Location": "/changed"});添加到默认值。

switch (request.url) {
    case "/somescript" :
        response.writeHead(200, {"Content-Type": "text/javascript"});
        response.write(somescript);
        break;      
    case "/changed" :
        response.writeHead(200, {"Content-Type": "text/plain; charset=UTF-8"});
        response.write(changedhtml);
        break;
    default :
        response.writeHead(301, {"Location": "/changed"});`
}
response.end();